简体   繁体   中英

Difference between initWithNibName and initWithCoder

任何人都可以解释我何时使用initWithNibName以及何时使用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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM