开发者

initWithNib vs setting file owner to viewcontroller subclass

I'm not understanding the role of nib files vs setting the file owner to a viewcontroller subclass. If I set the file owner of the nib to my subclass, then when I instance the subclass the nib开发者_JAVA技巧 seems to load with all its subviews. Why would I need initWithNib?

In another case, I noticed when I created a tableview inside a nib, added a searchbar to the tableview and set the file owner to a subclass of uitableviewcontroller, the search bar would not show up unless I used initWithNib. Why would I need initWithNib in this case when I don't in the previous?


I'm having a hard time making sense of your question.

-initWithNibName:bundle: is the designated initializer for UIViewController. You can pass nil for the nib name and bundle if you want, and in that case the default behavior is to look for a .xib file with the same name as that of the view controller subclass in the app bundle. So it's not uncommon to have a view controller and .xib with identical names, and to simply pass nil for the name and bundle. You could, however, have several different nibs that can all work with the same view controller subclass. For example, you might have one nib laid out in portrait orientation and another in landscape, and you'd decide which to use based on the orientation of the device.

File's Owner is an object in the nib that's a proxy for the object that loads the nib file. You can (and should) set its type so that Interface Builder will know what outlets and actions the object loading the file can be expected to provide, and thus what can be connected to the File's Owner proxy. When the app runs and an object loads a nib, any objects inside that nib that are connected to File's Owner will instead by connected to the object that loaded the file. This is the primary mechanism by which objects inside the nib can communicate with the rest of the application.

So, although File's Owner and -initWithNibName:bundle: both play a role in loading a nib, they're very different roles and mostly orthogonal. If you're successfully calling -init on some of your view controllers and finding that the nib is loaded anyway, it's likely that the implementation of -init calls -initWithNibName:bundle: and passes nil for both parameters, as described above.


There is a fallback logic which uses the name of the view controller class as a default for the lookup of the nib. That's why you don't have to provide it explicitly - the system finds it for you as long as the name corresponds. On the other hand, if you choose to give your nib a different name, then you might find initWithNib useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜