23

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

Lithu T.V
  • 19,955
  • 12
  • 56
  • 101

2 Answers2

52

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.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • 1
    Thank You ,One doubt .My methods contain block implementation inside it(Restkit Post and get methods).will it be affected by any means? – Lithu T.V Mar 03 '13 at 14:43
  • 1
    This is no problem. Blocks are free to run inside of other blocks, and queues can freely dispatch thing that run on other (or the same) queues. The internal implementation details shouldn't impact you at all here. – Rob Napier Mar 03 '13 at 19:14
0

Neat little method I got from Googles iOS Framework they rely on pretty heavily:

- (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {


    if (signInDoneSel) {
        [self performSelector:signInDoneSel];
    }

}
ChuckKelly
  • 1,742
  • 5
  • 25
  • 54
  • How to call the method from another? `runSigninThenInvokeSelector:(SEL)signInDoneSel`? –  Jul 09 '16 at 18:13