IOS - Delegate vs Notification

感情迁移 提交于 2019-12-07 04:39:41

问题


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?


回答1:


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.




回答2:


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.




回答3:


3: A callback function. (like 1, but without the faff of declaring a protocol specifically just 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)
    }
}



回答4:


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



来源:https://stackoverflow.com/questions/27647047/ios-delegate-vs-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!