开发者

Difference between initWithNibName and initWithCoder

Can anyone please explain开发者_StackOverflow me about when to use the initWithNibName and when to use initWithCoder?


initWithNibName: is usually used with a view controller object. The idea is that you have a NIB file (or XIB, same thing) that has a UIView (or NSView) you've already designed in Interface Builder. When your view controller launches, it has a view property and outlet that you would have to draw yourself -- except that you've already designed it in IB. So this constructor allows you to fire up the new controller object and tells it in which NIB file to look for its view. Discussion of wiring your NIB itself to make sure this is successful is a little beyond the topic here.

initWithCoder: has another task altogether. When you have serialized an object using encodeWithCoder:, you will eventually need to unserialize (or, "decode") that data to turn it back into an object of your class.

Anyway, to recap: You would implement encodeWithCoder: and initWithCoder: on your class only if you wanted your object to support the NSCoding protocol. You use initWithNibName: (typically you don't implement it yourself) when you want to fire up an object that can initialize its properties with objects archived in a NIB file.

There's a really great over-view of NSCoding over here.


Storyboard

You should prefer -initWithCoder: to -initWithNibName since only the former is invoked when loading a view from Storyboard.


From Apple's Documentation:

InitWithCoder encodes an object for archiving. A coder instructs the object to do so by invoking encodeWithCoder: or initWithCoder:. encodeWithCoder: instructs the object to encode its instance variables to the coder provided...

InitWithNibName Returns an NSNib object initialized to the nib file in the specified bundle. After the nib file has been loaded, the NSNib object uses the bundle’s resource map to locate additional resources referenced by the nib. If you specified nil for the bundle parameter, the NSNib object looks for those resources in the bundle associated with the class of the nib file’s owner instead. If the nib file does not have an owner, the NSNib object looks for additional resources in the application’s main bundle.

The former is used for encoding individual objects in your code, the latter is used to retrieve a NSNib file containing resource objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜