简体   繁体   中英

ios: waiting for method to finish executing before continuing

I am new to IOS development and am currently facing a problem.

When method A is called, it calls method B and then it wait for delegate connectionDidFinish which connectionDidFinish will execute MethodC.

My question is how do I ensure that methodA to methodC has finished executing before executing NSLog?

I found that a way to solve this problem is to use notification center. Send notification to me after finishing executing methodC. I don't think this is a good solution. Is there another way to do this?

Example:

 [a methodA];
 NSLog(@"FINISH");

If any of those methods perform actions asynchronously, you can't. You'll have to look into a different way of doing this. I personally try to use completion blocks when ever I can, although it's perfectly fine to do this other ways, like with delegate methods. Here's a basic example using a completion block.

- (void)someMethod
{
    [self methodAWithCompletion:^(BOOL success) {
        // check if thing worked.
    }];
}

- (void)methodAWithCompletion:(void (^) (BOOL success))completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{

        // go do something asynchronous...

        dispatch_async(dispatch_get_main_queue(), ^{

            completion(ifThingWorked)

        });
    });
}

In the code you posted, methodA must finish executing before the log statement will execute.

However, if methodA starts an asynchronous process that takes a while to finish and returns before it is finished, then you need to do something different. Usually you don't want to freeze the user interface while you are waiting, so you set up a delegate, pass in a completion block, or wait for an "ok, I'm done" notification.

All those are very valid, good ways to solve the problem of waiting for asynchronous tasks to finish running.

Newer APIs are starting to use completion blocks. Examples are:

  • presentViewController:animated:completion:, which takes a completion block that gets called once the new view controller is fully on-screen and "ready for business.
  • animateWithDuration:animations:completion:, which takes a completion block that gets executed once the animation is finished, and
  • sendAsynchronousRequest:queue:completionHandler:, which starts an asynchronous URL request (usually an HTTP GET or PUT request) and provides a completion block that gets called once the request has been completed (or fails)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM