【问题标题】:How should I be communicating asynchronously between models and controllers in objective c?我应该如何在目标 c 中的模型和控制器之间进行异步通信?
【发布时间】:2011-05-16 03:24:43
【问题描述】:

我有一个 Authenticator 类,它有一个使用 API 密钥进行身份验证的方法和另一个使用电子邮件地址和密码进行身份验证的方法。身份验证是通过异步 HTTP 请求完成的。

我有一个 LoginController 来管理用户将输入其电子邮件/密码的视图。

这是一个代码sn-p:

// 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]];
}

我的Authenticator 对象进行身份验证,我的LoginController 需要异步结果(成功或失败)。

Objective C 从模型到控制器的异步通信方式是什么?

【问题讨论】:

    标签: objective-c coding-style


    【解决方案1】:

    您可以在此处使用的一种可能模式是委托。

    您可以定义一个AuthenticatorDelegate 协议并让您的LoginController 符合它。比如:

    @protocol AuthenticatorDelegate
    - (void) authenticationSuccessful;
    - (void) authenticationFailedWithError:(NSError *)error
    @end
    
    @interface Authenticator : NSObject
    {
        ...
        id <AuthenticatorDelegate> delegate;
    }
    @property (assign) id <AuthenticatorDelegate> delegate;
    
    @end
    

    您的 LoginController 将被声明为

    @interface LoginController : UIViewController <AuthenticatorDelegate>
    ...
    

    当你初始化它时,你设置了委托

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

    然后当您的 Authenticator 对象收到结果时,您只需在委托上调用适当的方法。

    当然,这只是其中一种可能性。其他方法可以使用代码块或目标/选择器对。

    【讨论】:

    • 就是这样。我通常会写一个像上面这样的正式协议,但如果你只使用这两个类,则没有必要。
    • @nfm:在这种情况下,informal protocol 可能就足够了,就像另一种选择一样。例如,NSURLConnectionDelegate 就是这样工作的。
    【解决方案2】:

    让验证器成为你的 NSURLConnection 的代表,然后覆盖

    connectionDidFinishLoading:
    

    connection:didFailWithError:
    

    在身份验证器中保存对LoginController 的引用,然后当您收到connectionDidFinishLoading: 时评估响应并将消息发送回 LoginController

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-10
      • 2013-10-02
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多