IOS - Delegate vs Notification

Shlomi Schwartz picture Shlomi Schwartz · Dec 25, 2014 · Viewed 7.2k times · Source

Would like to have your opinion regarding the following architecture:

In My app I have a static class (LoginManager) that handles an asynchronous login. Once the login phase is completed the app should response and transition to another state.

I have 2 implementation suggestions

  1. 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)
        }
    
    }
    
  2. using a Notification:

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

Q:What would be the best approach?

Answer

ChintaN -Maddy- Ramani picture ChintaN -Maddy- Ramani · Dec 25, 2014

For

  1. Delegate/Protocol

It is generally used when you want to update or done any procedure in you previous controller from current view controller. so if you want to update values in previous view controller then Delegate/Protocol is preferable.

So it is basically 1-to-1 Relation.

  1. Notification

It is generally used when you want to update values in your view controller from any other viewcontroller. so its basically 1-to-n relation.

So use this type as per your requirement.

Maybe this will help you.