我在 decodeObjectForKey: 调用上得到一个 EXC_BAD_ACCESS。如果有人能在这里发现一个明显的错误,我将不胜感激:
- (NSData *)serialize:(id <NSCoding>)object {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver setOutputFormat:NSPropertyListBinaryFormat_v1_0];
[archiver encodeObject:object forKey:@"myobject"];
[archiver finishEncoding];
return data;
}
- (id)deserialize:(NSData *)data {
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
unarchiver.delegate = self;
id object = [unarchiver decodeObjectForKey:@"myobject"];
[unarchiver finishDecoding];
return object;
}
NSCoding 协议是这样实现的:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self != nil) {
_fields = [aDecoder decodeObjectForKey:@"fields"];
_entries = [aDecoder decodeObjectForKey:@"entries"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_fields forKey:@"fields"];
[aCoder encodeObject:_entries forKey:@"entries"];
}
我不能使用 +unarchiveObjectWithData: 因为我需要设置一个委托来更新反序列化对象:
- (id)unarchiver:(NSKeyedUnarchiver *)unarchiver didDecodeObject:(id)object {
if([[object class] isSubclassOfClass:[LCEntity class]]) {
[object setStore:_store];
}
return nil;
}
我正在使用 ARC - 所以不用担心内存管理问题。