问题
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
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) } }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
- 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.
- 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