creating methods with Completion Handler

Discussion in 'iOS Programming' started by hassoon, Aug 19, 2013.

  1. hassoon macrumors regular

    Joined:
    Jun 8, 2009
    #1
    Hi, in my app i wanna be able to call a method from a method i'm currently in when it finishes executing it's own code asynchronously. however, i don't know how to implement such a paradigm not even have a clue how to. i've user many methods with completion handlers in the ios API but i want to create one. can anybody point me to a source or give me an example on how to do that? Thank you!
     
  2. mjohnson1212 macrumors member

    Joined:
    Nov 15, 2007
    #2
    You can use a block passed into the initiating call. Store the block and call it when the async call finishes.

    Depending on how you are running the async code you might need to marshal the block call back to the main thread with a dispatch async on the main queue if your callback is updating the UI.
     
  3. dantastic macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #3
    Consider the following

    Code:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    	
    	// doing serious heavy work...
    	myInt = 1000 * 1000;
    	
    	dispatch_async(dispatch_get_main_queue(), ^{
    		
    		[self myMethodToUpdateUIAfterHeavyWork];
    	});
    });
    If you do your heavy work inside a block like this you can then call your next method once the work has completed. If your next method doesn't have to run on the main thread you can just call it after the calculation of myInt is done.
     

Share This Page