Lit*_*T.V 23 function objective-c ios
我有2个方法可以在一个按钮点击事件上执行,method1:并且method2:.Both有网络调用,因此无法确定哪个方法将首先完成.
我必须methodFinish在完成method1:和method2之后执行另一个方法:
-(void)doSomething
{
[method1:a];
[method2:b];
//after both finish have to execute
[methodFinish]
}
Run Code Online (Sandbox Code Playgroud)
除了典型的以外,我怎样才能做到这一点 start method1:-> completed -> start method2: ->completed-> start methodFinish
阅读有关街区的信息.我是块新手.可以帮我写一篇文章吗?任何解释都会非常有用.谢谢.
Rob*_*ier 52
这就是调度组的用途.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
// Add a task to the group
dispatch_group_async(group, queue, ^{
[self method1:a];
});
// Add another task to the group
dispatch_group_async(group, queue, ^{
[self method2:a];
});
// Add a handler function for when the entire group completes
// It's possible that this will happen immediately if the other methods have already finished
dispatch_group_notify(group, queue, ^{
[methodFinish]
});
Run Code Online (Sandbox Code Playgroud)
调度组是ARC管理的.它们由系统保留,直到它们的所有块运行,因此在ARC下它们的内存管理很容易.
另请参阅dispatch_group_wait()是否要在组完成之前阻止执行.