IOS - delegation versus notification

I would like to express my opinion on the following architecture:

In my application, I have a static class (LoginManager) that handles asynchronous login. After completing the sign-in phase, the application should respond and transition to a different state.

I have 2 options for implementation

  • using a delegate:

    import Foundation
    
    protocol LoginManagerDelegate{
        func onLogin(result:AnyObject)
    }
    
    class LoginManager {
        struct Wrapper {
            static var delegate:LoginManagerDelegate?
        }
    
        class func userDidLogin(result){            
             Wrapper.delegate?.onLogin(result)
        }
    
    }
    
          

  • via notification:

    import Foundation
    
    class LoginManager {
    
        class func userDidLogin(result){            
             NSNotificationCenter.defaultCenter().postNotificationName("onLogin", object: result)
        }
    
    }
    
          

Q : What would be the best approach?

+3


source to share


4 answers


If a

func onLogin (result: AnyObject)

Executed in only one class, I would go with a delegate ... More suitable for a ratio of 1 to 1 .



If it 's a 1 to n relationship , I would go with Notification .

I don't like to rely on notification (personal taste), so I usually handle login / logout transitions in my AppDelegate, which allows me to use the Delegate pattern.

+6


source


For

  • Delegate / Protocol

Typically used when you want to update or execute a procedure in a previous controller from the current controller. so if you want to update values ​​in a previous view controller then delegate / protocol is preferable.

So this is basically a 1 to 1 ratio.



  1. Notification

Typically used when you want to update values ​​in your view controller from any other view manager. so it's basically a 1-to-n ratio.

Therefore, use this type as per your requirement.

Maybe this will help you.

+6


source


3: callback function. (for example, 1, but without barriers to declaring a protocol specifically for this purpose).

class LoginManager {
    // using this singleton makes me feel dirty
    struct Wrapper {
        // this AnyObject too...
        static var callback: ((result: AnyObject)->())?
    }

    class func userDidLogin(result){            
         Wrapper.callback?(result)
    }
}

      

+1


source


I would go for a completion block with a delegate implemented. By the way, as a good practice NSNotification should not be fired / used to transition. Better to use delegates.

0


source







All Articles