Search code examples
objective-ciosnibgrand-central-dispatchloadnibnamed

loading a nib on a background thread


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.


Solution

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