Reputation: 622
i've got problems using the NSKeyedArchiver/NSKeyedUnarchiver for saving my object.
I added the methods - (id)initWithCoder:(NSCoder *)decoder
and - (void)encodeWithCoder:(NSCoder *)encoder
. The problem is when i try to save the object it doesn't work correctly.
I could imagine a problem (but I'm not sure if it is the problem ;) ). I have some arrays within my object. They contain more objects (I implemented both of the "Coder"-Methods as well). So does the array call the methods in it's objects?
Any possible solution??
Thanks!!
Upvotes: 0
Views: 1046
Reputation: 11113
In the header file indicate that your class will implement the NSCoding
protocol, like <NSCoding>
In the encodeWithCoder
method you need to encode all the fields you want to save like so:
[encoder encodeObject:array1 forKey:@"array1"];
Then in the initWithCoder
method, decode the fields that were encoded:
array1 = [coder decodeObjectForKey:@"array1"];
Be sure that any encoded containers only contain objects that also implement the NSCoding
protocol. This could be core classes such as NSString
, NSNumber
, NSArray
, NSDictionary
, as well as your own custom object.
If your project is not using garbage collection you need to retain or copy the data retrieved from the archive like so:
array1 = [[coder decodeObjectForKey:@"array1"] retain];
Upvotes: 5