6

NSKeyedArchiver archivedDataWithRootObject: 的参数应该是我要保存的数组,还是转换为 NSData 的数组?

4

2 回答 2

16

虞姬的回答是对的。但更准确地说,您的数组元素必须实现协议并将您自己的代码填充到方法 initWithCoder: 和 encodeWithCoder: 中,例如:

- (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"];
}

然后你可以使用归档器和 unchariver,如:

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

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

更多信息,您可以参考“使用 NSCoding 归档 Objective-C 对象”。

于 2013-01-29T08:28:48.717 回答
14

要将通用数组转换为NSData,您需要一个存档器!如果你知道如何喂食NSData,你就知道如何使用NSKeyedArchiver。所以:

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

当然,你array需要实现的所有元素encodeWithCoder:

于 2010-09-19T16:42:57.267 回答