Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initWithNibName and initWithCoder

Tags:

iphone

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

like image 854
user482860 Avatar asked Oct 21 '10 10:10

user482860


3 Answers

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.

like image 131
Billy Gray Avatar answered Nov 20 '22 08:11

Billy Gray


Storyboard

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

like image 26
SwiftArchitect Avatar answered Nov 20 '22 09:11

SwiftArchitect


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.

like image 2
Jordan Avatar answered Nov 20 '22 07:11

Jordan