Arjun
Arjun

Reputation: 89

IOS/Objective-C: returning to main thread

I think I understand how the following works but would appreciate confirmation.

dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL: dataUrl];
    [self fetchData:data];//go to web, get data and store in core data
}
dispatch_async(dispatch_get_main_queue(), ^{
    //display new data on main thread.
}

My question is can I take it for granted that the display on the main thread will not take place until after the conclusion of everything that occurs in the background--no matter how long?

The reason I would appreciate confirmation is that occasionally I am observing some issues with the display. Want to be sure the display is not trying to access core data when background thread has not finished saving to it.

Upvotes: 0

Views: 4280

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Your code is not correct. You are attempting to update the UI long before the data is retrieved from the URL.

You need:

dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL: dataUrl];
    [self fetchData:data];//go to web, get data and store in core data
    dispatch_async(dispatch_get_main_queue(), ^{
        //display new data on main thread.
    }
}

This code also assumes that fetchData: is not asynchronous meaning that it doesn't return until the data has been fetched and updated.

Upvotes: 2

Related Questions