NSKeyedArchiver archivedDataWithRootObject:

node ninja picture node ninja · Sep 19, 2010 · Viewed 16.7k times · Source

Is the parameter for NSKeyedArchiver archivedDataWithRootObject: supposed to be the array I am trying to save, or the array converted into NSData?

Answer

Bruce Lee picture Bruce Lee · Jan 29, 2013

Yuji's answer is right. but more accurately, your element of an array have to implement protocol and fillin your own code to methods initWithCoder: and encodeWithCoder: like:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.title = [decoder decodeObjectForKey:@"title"];
        self.author = [decoder decodeObjectForKey:@"author"];
        self.published = [decoder decodeBoolForKey:@"published"];
    }
    return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:title forKey:@"time"];
    [encoder encodeObject:author forKey:@"author"];
    [encoder encodeBool:published forKey:@"published"];
}

then you can use the archiver and unchariver like:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notes];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"notes"];

NSData *notesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"notes"];
NSArray *notes = [NSKeyedUnarchiver unarchiveObjectWithData:notesData];

For more, you can get reference "Archiving Objective-C Objects with NSCoding".