Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use encodeWithCoder: and initWithCoder: on the iPhone?

As my question in the subject above states, what requirements do you typically have to meet in order to say "Ok, I need encodeWithCoder: and initWithCoder: instantiation for this"? Typically you can write object state to NSUserDefaults, so I'm curious when do you experts decide to use one vs the other?

like image 924
Coocoo4Cocoa Avatar asked Apr 30 '09 23:04

Coocoo4Cocoa


3 Answers

initWithCoder: is used by the OS when un-archiving XIB files; if you look closely, you'll see that initWithFrame: is not called for views you create in your XIB; they'll have initWithCoder: called instead.

like image 55
Ben Gottlieb Avatar answered Oct 19 '22 20:10

Ben Gottlieb


User defaults is, basically, a property list. Property lists are similar to JSON and can only store specific types of data -- NSString, NSNumber, NSData, NSDate, NSArray, NSDictionary. If you try to store anything else in a user default, you'll get an exception. Property lists also can't handle arbitrary object graphs, only trees.

You could always take your custom state and convert it into a property-list compatible data structure, then store it in user defaults; but then you're basically implementing an object serialization mechanism, and you might as well use the more powerful one that's already provided by NSArchiver.

like image 22
Jens Alfke Avatar answered Oct 19 '22 20:10

Jens Alfke


NSCoder is the standard Cocoa method of implementing serialization. See Apple's Archives and Serializations Programming Guide for Cocoa for details.

like image 29
rpetrich Avatar answered Oct 19 '22 21:10

rpetrich