I need a little help with decodeBytesForKey using NSKeyedUnarchiver unarchiveObjectWithFile. I appear to be writing everything correctly but reading the data gives me a EXC_BAD_ACCESS error. I'm trying to deserialize data and have gotten confused by the various answers and examples out there. Can someone please point out what I am doing wrong?
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;
}
If I comment out the encoder and decoder lines for the data, I get the correct values back for everything else, but I need the data too.