user482860
user482860

Reputation: 101

Difference between initWithNibName and initWithCoder

Can anyone please explain me about when to use the initWithNibName and when to use initWithCoder?

Upvotes: 9

Views: 4045

Answers (3)

SwiftArchitect
SwiftArchitect

Reputation: 48524

Storyboard

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

Upvotes: 3

Billy Gray
Billy Gray

Reputation: 1747

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.

Upvotes: 6

Jordan
Jordan

Reputation: 21760

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.

Upvotes: 2

Related Questions