Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

objective c - How to write the method to execute after completion of two methods (ios)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...