问题描述
我是 IOS 开发的新手,目前遇到了一个问题.
I am new to IOS development and am currently facing a problem.
当方法 A 被调用时,它会调用方法 B,然后等待委托 connectionDidFinish
委托 connectionDidFinish
将执行 MethodC.
When method A is called, it calls method B and then it wait for delegate connectionDidFinish
which connectionDidFinish
will execute MethodC.
我的问题是如何确保methodA到methodC在执行NSLog之前已经执行完毕?
My question is how do I ensure that methodA to methodC has finished executing before executing NSLog?
我发现解决这个问题的方法是使用通知中心.执行完methodC后发送通知给我.我不认为这是一个好的解决方案.还有其他方法可以做到这一点吗?
I found that a way to solve this problem is to use notification center. Send notification to me after finishing executing methodC. I don't think this is a good solution. Is there another way to do this?
示例:
[a methodA];
NSLog(@"FINISH");
推荐答案
如果这些方法中的任何一个异步执行操作,则不能.你必须寻找一种不同的方式来做到这一点.我个人尽可能地尝试使用完成块,尽管以其他方式执行此操作完全没问题,例如使用委托方法.这是一个使用完成块的基本示例.
If any of those methods perform actions asynchronously, you can't. You'll have to look into a different way of doing this. I personally try to use completion blocks when ever I can, although it's perfectly fine to do this other ways, like with delegate methods. Here's a basic example using a completion block.
- (void)someMethod
{
[self methodAWithCompletion:^(BOOL success) {
// check if thing worked.
}];
}
- (void)methodAWithCompletion:(void (^) (BOOL success))completion
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{
// go do something asynchronous...
dispatch_async(dispatch_get_main_queue(), ^{
completion(ifThingWorked)
});
});
}
这篇关于ios:在继续之前等待方法完成执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!