开发者

How should I be communicating asynchronously between models and controllers in objective c?

开发者 https://www.devze.com 2023-03-05 22:45 出处:网络
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 reques

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:[pass开发者_JS百科wordField 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 AuthenticatorDelegate protocol and have your LoginController conform to it. Something like:

@protocol AuthenticatorDelegate
- (void) authenticationSuccessful;
- (void) authenticationFailedWithError:(NSError *)error
@end

@interface Authenticator : NSObject
{
    ...
    id <AuthenticatorDelegate> delegate;
}
@property (assign) id <AuthenticatorDelegate> delegate;

@end

your LoginController would be declared as

@interface LoginController : UIViewController <AuthenticatorDelegate>
...

and when you initialize it you set the delegate

- (void)awakeFromNib {
    self.authenticator = [[Authenticator alloc] init];
    self.authenticator.delegate = self;
}

and then when your Authenticator objects 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.


make authenticator the delegate of the your NSURLConnection, then override the

connectionDidFinishLoading:

and

connection:didFailWithError:

save a ref to LoginController in the authenticator, then when you get connectionDidFinishLoading: you evaluate the response and send the message back to LoginController.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号