Jim
Jim

Reputation: 5960

Is it safe to instantiate UI object on background thread?

I'm not clear to what extent working with UI objects is not safe. I have some code that I just moved to another queue (using NSOperation and NSOperationQueue). I am reviewing where I need to clean up non-safe code and ran accross this:

alertNoDatabaseSelected = [[[UIAlertView alloc] 
    initWithTitle:NSLocalizedString(@"You Haven't Enabled Any Databases", nil) 
    message:[NSString stringWithFormat:NSLocalizedString(@"You can't search unless you choose at least one database in your settings.", nil), self.currentSearchEntity.keywords] 
    delegate:self cancelButtonTitle:NSLocalizedString(@"Settings", nil) 
    otherButtonTitles:nil] autorelease];
[alertNoDatabaseSelected show];

Are both of these lines unsafe outside of the main thread? I do have some crashing behavior, and this looks like the first type of refactoring I should look at doing.

UPDATE This could be a much broader concern. I have two NSManagedObjectContexts, one in th emain thread, and one in another thread. When I synchronize these contexts, a lot of UI updatings (particularly the table views) can occur. I want to know if I need to take any special measures to make sure that the synchronization kicks all this off on the main thread automatically or do I have to do something to make it happen that way? (I may need to write another question on this.)

Upvotes: 2

Views: 144

Answers (1)

Tony
Tony

Reputation: 3478

The second line is definitely unsafe outside of the main thread. The alloc itself might be okay on a secondary thread but I don't know if the init... method is, and a prudent assumption would be that it's not safe.

You should schedule all your UI updates on the main thread. You can use [NSOperationQueue mainQueue] if you want to schedule them as NSOperation objects.

Upvotes: 1

Related Questions