我创建了 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];
}
或者我只是以错误的方式保存这些数据?非常感谢。
初始化数组的代码实际上并未创建 UIImageExtra 子类的实例。
UIImageExtra *illustration = (UIImageExtra *)[UIImage imageNamed:illustrationString];
返回一个 UIImage。铸造它并没有达到您的预期。
UIImageExtra *scaledIllustration = [illustration adjustForResolution];
is still只是一个 UIImage。
解决这个问题的一种简单但详细的方法是使 UIImageExtra 成为wrapper围绕 UIImage。包装器将有一个用于从 UIImage 进行初始化的类方法:
+ (UIImageExtra)imageExtraWithUIImage:(UIImage *)image;
然后你想要调用的每个 UIImage 方法都必须转发到包装的 UIImage 实例 - 还要小心地重新包装例如的结果-adjustForResolution
以免您再次得到一个未包装的 UIImage 实例。
一种更复杂的 Objective-C 方法是将您想要的功能添加到Category在 UIImage 上,然后使用方法混合将 NSCoding 方法替换为您的类别实现。其中棘手的部分(除了所需的 Objective-C 运行时体操)是在哪里存储“额外”数据,因为您无法在类别中添加实例变量。 [标准答案是有一个后备字典,由 UIImage 实例的某种合适的表示形式(如包含其指针值的 NSValue)作为键,但正如你可以想象的那样,簿记很快就会变得复杂。]
退后一步,我对新的 Cocoa 程序员的建议是:“想一个更简单的方法。如果你想做的事情这么复杂,那就尝试别的方法。”例如,写一个简单的ImageValue
类有一个-image
方法和-extraInfo
方法(并实现 NSCoding 等),并将其实例存储在数组中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)