Search code examples
iphoneiosthread-safetyperformselector

How to ensure thread synchronization


I have a method myButtonAction which performs some heavy calculations, which I need to run on a background thread, while I am loading a view indicating "Task progress" in the main thread. As soon as the, background thread completes executing the method, I need to remove the "task progress" view and load another view in the main thread.

[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];

The problem I am facing is that, before myButtonAction completes execution, the LoadView completes its execution. How can I make sure that LoadView starts execution only after myButtonAction completes its execution.

Note: myButtonAction has its method definition in another class.


Solution

  • Use Grand Central Dispatch:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self myButtonAction];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self LoadView];
        });
    });
    

    Or, if you want to stay with performSelector methods:

    [self performSelectorInBackground:@selector(loadViewAfterMyButtonAction) withObject:nil];
    

    where

    - (void)loadViewAfterMyButtonAction
    {
        [self myButtonAction];
        [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
    }