Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS - Delegate vs Notification

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?

like image 530
Shlomi Schwartz Avatar asked Dec 25 '14 12:12

Shlomi Schwartz


People also ask

What is delegate and notification?

Delegate is passing message from one object to other object. It is like one to one communication while nsnotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can't respond to that event.

What does delegate mean in iOS?

What is delegate methods in iOS? It is an easy and influential pattern in which one object in a program works on behalf of or in coordination with, another object. The delegating object keeps a reference to the other object and at the suitable time sends a message to it.

What is the difference between delegate and closure?

Difference between protocol Delegate and Closures –In the protocol method, we use the call by delegate method then use it but in closer, we can call it directly, there is no need for the delegate method.

What is delegate in iOS Swift?

In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behavior of another object.


1 Answers

If the

func onLogin(result:AnyObject)

Is implemented in only one class, I would go with the delegate. More appropriate for a 1 to 1 relation.

If it's an 1 to n relation, I would go with the Notification.

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

like image 60
Mehdi.Sqalli Avatar answered Sep 18 '22 13:09

Mehdi.Sqalli