NSCoding协议问题

时间:2010-10-08 16:42:33

标签: objective-c cocoa nscoding

我想将归档(NSCoding)协议添加到我的模型类中,然后实现方法encodeWithCoder:(NSCoder*)coderinitWithCoder:(NSCoder*)coder。 MyModelClass有2个实例变量(NSString和NSImage),所以我使用encodeObject:(id)object forKey:(NSString*)string方法对对象进行编码,加上特定键的值。但我一直得到错误:

*** -encodeObject:forKey: only defined for abstract class. Define -[NSArchiver encodeObject:forKey:]!

这是我的NSCoding方法代码:

- (id)initWithCoder:(NSCoder *)coder {
 [super init];
 mainPath = [[coder decodeObjectForKey:@"mainPath"] retain];
 icon = [[coder decodeObjectForKey:@"icon"] retain];

 return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
 NSLog(@"encode with coder is called");
 [coder encodeObject:mainPath forKey:@"mainPath"];
 [coder encodeObject:icon forKey:@"icon"];

}

这就是我在控制器类中调用它们的方式:

id object = [assetArray objectAtIndex: [[rows lastObject] intValue]];

 if ([object isKindOfClass:[ItemAssetModel class]])
  NSLog(@"object is correct");
 else
  return NO;

 NSData *data = [NSArchiver archivedDataWithRootObject: object];

如果我用encodeObject:(id)obj forKey:(NSString*)str更改encodeObject:(id)obj,则错误停止,但结果是,存档数据不会复制实例变量值(cmiiw)。我会错过这个吗?

感谢。 赫布

1 个答案:

答案 0 :(得分:8)

尝试使用NSKeyedArchiver而不是NSArchiver。