我创建了 UIImage (UIImageExtra) 的子类,因为我想包含额外的属性和方法。
我有一个包含此自定义类实例的数组。但是,当我保存数组时,UIImageExtra 类中的额外数据似乎没有保存。
UIImageExtra 符合 NSCoding,但没有调用 initWithCoder 或 encodeWithCoder,因为我添加的 NSLog 语句没有打印。
我保存数组的方法如下所示:
- (void)saveIllustrations {
if (_illustrations == nil) {
NSLog(@"Nil array");
return;
}
[self createDataPath];
//Serialize the data and write to disk
NSString *illustrationsArrayPath = [_docPath stringByAppendingPathComponent:kIllustrationsFile];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:_illustrations forKey:kIllustrationDataKey];
[archiver finishEncoding];
[data writeToFile:illustrationsArrayPath atomically: YES];
}
并且 UIImageExtra 具有以下用于保存的委托方法:
#pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
NSLog(@"Encoding origin data!");
[super encodeWithCoder:aCoder];
[aCoder encodeObject:originData forKey:kOriginData];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:(NSCoder *) aDecoder]) {
NSLog(@"Decoding origin data");
self.originData = [aDecoder decodeObjectForKey:kOriginData];
}
return self;
}
我首先创建数组的代码如下所示(以防提供任何线索)
for (NSDictionary *illustrationDict in illustrationDicts) {
NSString *illustrationString = [illustrationDict objectForKey:@"Filename"];
NSNumber *xCoord = [illustrationDict objectForKey:@"xCoord"];
NSNumber *yCoord = [illustrationDict objectForKey:@"yCoord"];
UIImageExtra *illustration = (UIImageExtra *)[UIImage imageNamed:illustrationString];
//Scale the illustration to size it for different devices
UIImageExtra *scaledIllustration = [illustration adjustForResolution];
NSValue *originData = [NSValue valueWithCGPoint:CGPointMake([xCoord intValue], [yCoord intValue])];
[scaledIllustration setOriginData:originData];
[self.illustrations addObject:scaledIllustration];
}
还是我只是想以错误的方式保存这些数据?非常感谢。