我应该如何在 Objective C 中的模型和控制器之间进行异步通信?
我有一个 Authenticator 类,它有一个使用 API 密钥进行身份验证的方法和另一个使用电子邮件地址和密码进行身份验证的方法。身份验证是通过异步 HTTP 请求完成的。
我有一个 LoginController
来管理用户将在其中输入电子邮件/密码的视图。
下面是一个代码片段:
// 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 方式是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在这里使用的一种可能的模式是委托。
您可以定义一个 AuthenticatorDelegate 协议并让您的 LoginController 遵守它。类似于:
您的
LoginController
将被声明为,当您初始化它时,您设置委托
,然后当您的
Authenticator
对象收到结果时,您只需在委托上调用适当的方法。当然这只是其中一种可能性。其他方法可以使用代码块或目标/选择器对。
One possible pattern you could use here would be a delegate.
You could define a
AuthenticatorDelegate
protocol and have yourLoginController
conform to it. Something like:your
LoginController
would be declared asand when you initialize it you set the delegate
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.
让authenticator成为你的NSURLConnection的委托,然后覆盖
并
保存对authenticator中的
LoginController
的引用,然后当你得到connectionDidFinishLoading:
时,你评估响应并发送消息回到登录控制器
。make authenticator the delegate of the your NSURLConnection, then override the
and
save a ref to
LoginController
in the authenticator, then when you getconnectionDidFinishLoading:
you evaluate the response and send the message back toLoginController
.