保存自定义对象的NSArray

我创build了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; } 

我第一次创build数组的代码看起来像这样(如果提供任何线索)

  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]; } 

或者我只是想以错误的方式保存这些数据? 非常感谢。

您的代码来初始化arrays实际上并没有创build您的UIImageExtra子类的实例。

 UIImageExtra *illustration = (UIImageExtra *)[UIImage imageNamed:illustrationString]; 

返回一个UIImage。 施放它不会做你想要的。

 UIImageExtra *scaledIllustration = [illustration adjustForResolution]; 

仍然只是一个UIImage。

一个简单而又冗长的方法是使UIImageExtra成为UIImage的一个包装 。 包装将有一个从UIImage初始化的类方法:

 + (UIImageExtra)imageExtraWithUIImage:(UIImage *)image; 

然后,你想要调用的每个UIImage方法都必须转发到包装的UIImage实例 – 也要小心重新包装例如-adjustForResolution的结果,以免再次得到一个解包的UIImage实例。

更复杂的Objective-C方法是在UIImage的Category中添加所需的function,然后使用方法swizzling将NSCoding方法replace为类别实现。 这个(除了所需的Objective-C运行时体操)的棘手部分是存储“额外”数据的地方,因为你不能在一个类别中添加实例variables。 [标准答案是有一个由UIImage实例的某个合适表示(如包含其指针值的NSValue)键入的旁视字典,但正如您可以想象的那样,簿记可以变得更加复杂。

回想一下,我对一个新的Cocoa程序员的build议是:“想一个更简单的方法,如果你想要做的是复杂的,那就试试其他的东西。 例如,编写一个具有-image方法和-extraInfo方法(并实现NSCoding等)的简单ImageValue类,并将其存储在您的数组中。

初始化后,您不能将对象添加到NSArray。 使用NSMutableArray,这可能是问题。