Saving Array to Plist file that contains Custom Objects iPhone

Shri picture Shri · Nov 13, 2011 · Viewed 8.1k times · Source

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 [array writeToFile....], I found that writeToFile fails because the array contains custom objects of XYZ class.

The possible solution to this is to convert the objects to NSData. What are the different ways of achieving this?? I found that NSCoding is suitable but cant understand how to use it. Any help will be greatly appreciated.

Answer

Yannick Loriot picture Yannick Loriot · Nov 13, 2011

There is a very good tutorial on the Ray Wenderlich's blog which explains how to work with the NSCoding.

Simply you just have to implement the *-(void)encodeWithCoder:(NSCoder )encode and *-(id)initWithCoder:(NSCoder )decoder methods in your object that respects the NSCoding protocol like that:

// Header
@interface AnObject: NSObject <NSCoding>

// Implementation
- (void) encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:ivar1 forKey:@"ivar1"];
    [encoder encodeFloat:ivar2 forKey:@"ivar2"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:coder];
    ivar1 = [[coder decodeObjectForKey:@"ivar1"] retain];
    ivar2 = [[coder decodeObjectForKey:@"ivar2"] retain];
    return self;
}

You can also check the official documentation here.