NSKeyedArchiver archivedDataWithRootObject:

妖精的绣舞 提交于 2019-12-05 08:07:49

To convert a generic array to an NSData, you need an archiver! If you know how to feed the NSData, you know how to use NSKeyedArchiver. So:

NSArray* array= ... ;
NSData* data=[NSKeyedArchiver archivedDataWithRootObject:array];

Of course all elements in your array needs to implement encodeWithCoder:.

Bruce Lee

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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!