cocoainterfaceembedbuilderawakefromnib

Why is awakeFromNib being called twice when loading nib in nib?


I have two nibs: Parent.xib and Child.xib.

I've included the Child nib inside the Parent nib to simplify binding. I set the subview programmatically in loadView. The problem is, awakeFromNib is getting called twice in Child's controller.

I think I understand why this is happening. When Parent finishes loading, it sends an awakeFromNib to its objects, and since Child is the file owner of its nib, it calls awakeFromNib on itself as well.

Am I understanding this right? I was originally under the impression that awakeFromNib should only be called once per instance. Am I not supposed to embed nib in nib?

See Sample Project: https://github.com/panupan/AwakeFromNibTest


Solution

  • There are situations where awakeFromNib can be called more than once per instance, such as the one you setup. Another case is a controller that loads more than one nib object. You can work around this if you really want to, but a better design is not to have to. From the NSNibAwaking Protocol Reference:

    It is recommended that you maintain a one-to-one correspondence between your File’s Owner objects and their associated nib files. Loading two nib files with the same File’s Owner object causes that object’s awakeFromNib method being called twice, which could cause some data structures to be reinitialized in undesired ways. It is also recommended that you avoid loading other nib files from your awakeFromNib method implementation.

    In your particular example, there is no reason to embed one nib file inside another one. You get the memory footprint disadvantage of having to load both of them into memory without the convenience of having all the objects in a single nib file. You should split them up and use NSObjectController instances in the nib files to deal with binding between them.