I have an Authenticator class which has a method to authenticate with an API key and another method to authenticate with an email address and password. Authentication is done with an async HTTP request.
I have a LoginController that is managing the view that the user will enter their email/password into.
Here’s a code snippet:
// LoginController
- (void)awakeFromNib {
self.authenticator = [[Authenticator alloc] init];
}
- (IBAction)authenticateWithEmailAndPassword: (id)sender {
// Async HTTP request, so we can't just check the return
// value to see if authentication was successful or not
[self.authenticator authenticateWithEmail:[emailField stringValue]
password:[passwordField stringValue]];
}
My Authenticator object does the authentication, and my LoginController needs the asynchronous result (success or failure).
What’s the Objective C way of communicating asynchronously from the model back to the controller?
One possible pattern you could use here would be a delegate.
You could define a
AuthenticatorDelegateprotocol and have yourLoginControllerconform to it. Something like:your
LoginControllerwould be declared asand when you initialize it you set the delegate
and then when your
Authenticatorobjects receive the result you just call the appropriate method on the delegate.Of course that’s just one of the possibilities. Other approaches could use code blocks or a target/selector pair.