Search code examples
objective-ccocoansnotificationcenternsnotifications

NSNotificationCenter - Way to wait for a notification to be posted without blocking main thread?


I'm using an AFNetworking client object which makes an asynchronous request for an XML document and parses it.

Also using NSNotificationCenter to post a notification when the document has finished parsing.

Is there a way to wait for a notification to be posted without blocking the main thread?

E.g code:

-(void)saveConfiguration:(id)sender {

    TLHTTPClient *RESTClient = [TLHTTPClient sharedClient];

    // Performs the asynchronous fetching....this works. 
    [RESTClient fetchActiveUser:[usernameTextField stringValue] withPassword:[passwordTextField stringValue]];

    /*
     * What do I need here ? while (xxx) ?
     */

    NSLog(@"Fetch Complete.");

}

Basically I'm wondering what sort of code I need in the above specified area to ensure that the function waits until the fetch has been completed ?

As it is right now I'll see "Fetch Complete." in the debug console before the fetch has been completed.

I tried adding a BOOL flag to the TLHTTPClient class:

BOOL fetchingFlag;

and then trying:

while([RESTClient fetchingFlag]) { NSLog(@"fetching...); } 

When this class receives the notification it sets RESTClient.fetchingFlag = FALSE; which should technically kill the while loop right? Except my while loop runs infinitely ?!


Solution

  • Basically I'm wondering what sort of code I need in the above specified area to ensure that the function waits until the fetch has been completed ?

    You need no code. Don't put anything in the method after you start the fetch, and nothing will happen. Your program will "wait" (it will actually be processing other input) until the notification is recieved.

    In the notification handler method, put all the stuff that you need to do when the fetch is completed. This is (one of) the point(s) of notifications and other callback schemes -- your object won't do anything further until it gets the notification that it's time to act.

    Is there a way to wait for a notification to be posted without blocking the main thread?

    That's exactly how it works already.