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?
source to share
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.
source to share
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.
- 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.
source to share
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)
}
}
source to share