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?
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With