NSKeyArchiver & NSKeyUnarchiver

Hi - I am trying to learn how to write data to a .plist file and subsequently read it back using NSKeyArchiver & NSKeyUnarchive. I also would like to learn how to use encodeWithCoder: and initWithCoder: methods. Could anyone help me with an example please?

Thanks,
t.

That can be a pretty detailed topic. What sort of data are you trying to write to a .plist?

Hello Sahne,

Something simple as in:

NSString *title;
NSString *author;
BOOL published;

then provide values for each.

Regards,
t.

You really only need to get into encodeWithCoder: and initWithCoder: if you’re dealing with objects of your own class. If you only need dictionaries/records, you can read/write directly to property lists. Or you can use NSKeyedArchiver and archiveRootObject:toFile:.

Sorry if this sounds a bit vague, but the best approach is usually the simplest approach, and whether you can use that depends a bit on the complexity of the data. If you want to be able to add/extract bits at a time, rather than read/write all at once, you need to use the various encode and decode methods.

Your Ad Class from Chapter 7 of your book can be a good place to start. Apple’s Developer Docs have short examples but not always lead to the final objective. I can put somewhat a working script in Objective-c, but sometimes have difficulty translating it into ASOC.

I will post my code and hope I get some extra help.

Thanks,
t.

In theory, it should be like this:

on encodeWithCoder_(coder)
	coder's encodeObject_forKey_(my adDescription, "SMSAdDescription")
	coder's encodeObject_forKey_(my adColumns, "SMSAdColumns")
	coder's encodeObject_forKey_(my adDepth, "SMSAdDepth")
end encodeWithCoder_

on initWithCoder_(coder)
	continue init()
	set my adDescription to coder's decodeObjectForKey_("SMSAdDescription")
	set my adColumns to coder's decodeObjectForKey_("SMSAdColumns")
	set my adDepth to coder's decodeObjectForKey_("SMSAdDepth")
	return me
end initWithCoder_

But I’ve never tried using NSKeyedArchiver/NSKeyedUnarchiver on an AS class, and I’m not entirely confident it will work.

Thank you Shane, I will give it a try.

Thanks,
t.