Question

I just spent a day tracking down a really weird bug. It was a UILabel being overreleased, although in the code there was no over-releasing. If I commented out the release of the label, code was fine.

I tracked it down to a UIView that was being released in a background thread. Which didn't seem right as you're supposed to access all UI elements from the main thread. I then found a nib file that was being loaded in a background thread using:

[[NSBundle mainBundle] loadNibNamed:@"nib name" owner:self options:nil];

I don't need to go into the details of what the code was doing, but my question is:

If loadNibNamed is called in a background thread and the view loaded is cached by the nib loading process, then the main thread wants to load that nib too - but loads it from a cache. When my object is released - is the view loaded from the nib in the background also released in the background..?? Doesn't really make sense as the background thread would no longer exist anyway....

I don't know, but I resolved it by wrapping the loadNibNamed part of the code in a GCD dispatch onto main thread synchronously.

Was it helpful?

Solution

All UI-related operations should be done from the main thread.

OTHER TIPS

From Mike Ash's article

Dangerous Cocoa Calls

NSBundle This one has half of the problems of NSHost. NSBundle returns shared objects, but is not thread safe, so it's main-thread only. It's still safe to use from the main thread. The reason I mark it as dangerous is because the fact that it's unsafe to use from secondary threads is not really documented, but rather has to be inferred from the fact that it's not thread safe and the fact that the instances are shared, and it can be tempting to use it from other threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top