I have a class called XYZ inheriting from NSObject and an array which contains objects of XYZ. I need to write this array to a plist file on to documents directory. After trying
Conforming your XYZ class to the NSCoding protocol is indeed very suitable for what you're trying to do. To do so, add the NSCoding protocol to your class's interface declaration:
@interface XYZ
Then, you need implement encodeWithCoder: and initWithCoder: in your implementation. "Encode with coder" means "take your object's current state, and pack it into a generic object called an 'encoder'". "Init with coder" means "given an already-packed encoder object, configure yourself with the data packed into the encoder". In both of these methods, the 'encoder' will be an instance of NSCoder, which has a fairly simple interface for encoding ("packing") and decoding ("unpacking") basic types.
Here's a sample implementation:
@implementation XYZ
- (id)initWithCoder:(NSCoder*)encoder
{
self = [self init];
if (self)
{
self.myIntProperty = [encoder decodeIntForKey:@"myInt"];
}
return self;
}
– (void)encodeWithCoder:(NSCoder*)decoder
{
[decoder encodeInt:self.myIntProperty forKey:@"myInt"];
}
@end