如何编写两种方法完成后执行的方法(ios) [英] How to write the method to execute after completion of two methods (ios)

查看:137
本文介绍了如何编写两种方法完成后执行的方法(ios)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个方法在按钮单击事件上执行,比如 method1: method2:。网络调用,所以不能确定哪一个会先完成。



完成后我必须执行另一个方法 methodFinish method1:和method2:

   - (void)doSomething 
{

[method1 :一个];
[method2:b];

//完成后必须执行
[methodFinish]
}

我怎样才能达到这个比典型的 start method1: - >完成 - >启动方法2: - >完成 - > start methodFinish



阅读有关块的信息。我对块非常陌生。有人可以帮我编写一个块吗?非常有帮助。谢谢

解决方案

这就是调度组

  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); 
dispatch_group_t group = dispatch_group_create();

//将任务添加到组
dispatch_group_async(group,queue,^ {
[self method1:a];
});

//将另一个任务添加到组
dispatch_group_async(group,queue,^ {
[self method2:a];
});

//为整个组完成时添加处理函数
//如果其他方法已经完成,可能会立即发生
dispatch_group_notify(group,queue, ^ {
[methodFinish]
});

调度组由ARC管理。它们被系统保留,直到它们的所有块都运行完毕,所以它们的内存管理在ARC下很容易。

另见 dispatch_group_wait() code>如果你想阻止执行,直到组完成。


I have 2 methods to be executed on a button click event say method1: and method2: .Both have network calls and so cannot be sure which one will finish first.

I have to execute another method methodFinish after completion both method1: and method2:

-(void)doSomething
{

   [method1:a];
   [method2:b];

    //after both finish have to execute
   [methodFinish]
}

How can I achieve this other than the typical start method1:-> completed -> start method2: ->completed-> start methodFinish

Read about blocks..I am very new to blocks.Can anybody help me with writing one for this?And any explanation will be very helpful.Thank you

解决方案

This is what dispatch groups are for.

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

Dispatch groups are ARC managed. They are retained by the system until all of their blocks run, so their memory management is easy under ARC.

See also dispatch_group_wait() if you want to block execution until the group finishes.

这篇关于如何编写两种方法完成后执行的方法(ios)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆