Obj-C 中异步方法的同步版本
在 Objective-C 中制作异步方法的同步版本的最佳方法是什么(对于 iOS,如果它很重要的话)?
假设您有一个具有这两种方法的类:
- (void) asyncDoSomething; // Starts an asynchronous task. Can't be changed.
- (void) onFinishDoSomething; // Called when the task is finished
您将如何实现一个直到任务完成才返回的同步 doSomething
?
What's the best way to make a synchronous version of an asynchronous method in Objective-C (for iOS, in case it matters)?
Say you have a class with these two methods:
- (void) asyncDoSomething; // Starts an asynchronous task. Can't be changed.
- (void) onFinishDoSomething; // Called when the task is finished
How would you implement a synchronous doSomething
that does not return until the task is finished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,所以您可以声明一个全局布尔值,它会告诉您继续或等待,就在调用
- (void)asyncDoSomething;
方法之前,您将BOOL wait
设置为 < code>YES 并在等待响应的方法之后,在异步回调
- (void)onFinishDoSomething;
中,将布尔值设置为NO
;这样,您的方法仍然被称为异步,但后面的代码不会在响应之前执行。它会像同步一样等待。
Ok, so you can declare a global boolean that will tell you to continue or wait, just before calling your
- (void)asyncDoSomething;
method you set yourBOOL wait
toYES
and after the method you doto wait for your response, and in you async callback
- (void)onFinishDoSomething;
you set your boolean toNO
;This way, your method is still called asynchronous but the code after is not executed before the response. It will wait like if it was synchronous.
进入 asyncDoSomething 实现并删除 NSThread/NSOperation/callback 代码。
Go into the asyncDoSomething implementation and remove the NSThread/NSOperation/callback code.