Matt
Matt

Reputation: 2863

Making Objective-C code asyncronous without changing control flow

We currently have a method like the following:

-(void)DoTask{
   //METHOD 1

   //METHOD 2

   //METHOD 3

  //METHOD 4

}

We've found a bug and the fix requires us to make sure Method 3 is executed async. It happens throughout the entire system so we're hoping for a simple fix. Is there a way of just putting some type of wrapper method around the code that we need to run Async so the code flow doesn't need to change for the main method? So pretty much like:

-(void)DoTask{
   //METHOD 1

   //METHOD 2

   //WRAPPER START AROUND METHOD 3 TO MAKE IT ASYNC
   //METHOD 3
   //WRAPPER END AROUND METHOD 3 AFTER ASYNC HAS FINISHED FOR CODE TO GO ONTO METHOD 4

  //METHOD 4

}

Upvotes: 0

Views: 36

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66244

You can't* do that (what you're describing would be synchronous, not asyncronous).

You have a few options. You can call method 4 after method 3's asynchronous operation is complete:

-(void) doTask{
    //METHOD 1

    //METHOD 2

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //METHOD 3

        dispatch_async(dispatch_get_main_queue(), ^{
            //METHOD 4
        });
    });
}

You could also call method 4 first.

You could also use NSOperationQueue to chain your operations and set which operations require others to be complete. This allows you to run multiple operations concurrently.


* - Technically, you can do that, by blocking one thread until another completes, but you almost certainly shouldn't do that.

Upvotes: 1

Related Questions