我需要一些关于使用 NSKeyedUnarchiver unarchiveObjectWithFile decodeBytesForKey 的帮助。我似乎正确地编写了所有内容,但读取数据给了我一个 EXC_BAD_ACCESS 错误。我正在尝试反序列化数据,并且对那里的各种答案和示例感到困惑。有人可以指出我做错了什么吗?
for (NSString *item in directoryContent){
if ([[item pathExtension] isEqualToString:@"template"]) {
**// Next line is the problem line from the calling code:**
templateToRead = [[NSKeyedUnarchiver unarchiveObjectWithFile:[documentsDirectory stringByAppendingPathComponent:item]] mutableCopy];
IDImageTemplate *template = [[IDImageTemplate alloc] init];
template.templateData = templateToRead.templateData;
template.templateQuality = templateToRead.templateQuality;
template.templateSize = templateToRead.templateSize;
template.templateLocation = templateToRead.templateLocation;
[templatesRead addTemplate:template];
}
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInteger:self.templateSize forKey:@"templateSize"];
[encoder encodeBytes:(const unsigned char*)self.templateData length:self.templateSize forKey:@"templateData"];
[encoder encodeInt:self.templateQuality forKey:@"templateQuality"];
[encoder encodeInt:self.templateLocation forKey:@"templateLocation"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
self.templateSize = [decoder decodeIntegerForKey:@"templateSize"];
**// Next line is where the real problem is:**
self.templateData = (const char *)[decoder decodeBytesForKey:@"templateData" returnedLength:(NSUInteger *)self.templateSize];
self.templateQuality = [decoder decodeIntForKey:@"templateQuality"];
self.templateLocation = [decoder decodeIntForKey:@"templateLocation"];
}
return self;
}
如果我注释掉数据的编码器和解码器行,我会为其他所有内容返回正确的值,但我也需要数据。