我正在使用NSCoding将自定义类存档/取消归档作为数据持久性的方法。如果对象是NSObject的子类,它可以正常工作,但我也有自定义对象的子类。我是否需要更改initWithCoder:方法以及encodeWithCoder?现在,特定于子类的属性编码/解码很好,但是子类从超类继承的属性没有。有什么想法吗?这是基本结构:
@interface NewsItem : NSObject <NSCoding, NSCopying> {
//properties for the super class here
}
@implementation NewsItem
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:itemName forKey:kItemNameKey];
//etc etc
}
- (id)initWithCoder:(NSCoder *)coder {
if ( (self = [super init]) )
{
self.itemName = [coder decodeObjectForKey:kItemNameKey];
//etc etc
}
return self;
}
-(id)copyWithZone:(NSZone *)zone {
NewsItem *copy = [[[self class] allocWithZone: zone] init];
copy.itemName = [[self.itemName copy] autorelease];
//etc etc
return copy;
}
和子类:
@interface File : NewsItem {
NSString *fileSizeString;
//etc etc
}
@implementation File
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder]; //added this, but didn't seem to make a difference
[coder encodeObject:fileSizeString forKey:kFileSizeStringKey];
//etc etc
}
- (id)initWithCoder:(NSCoder *)coder {
if ( (self = [super init]) )
{
self.fileSizeString = [coder decodeObjectForKey:kFileSizeStringKey];
//etc etc
}
return self;
}
-(id)copyWithZone:(NSZone *)zone {
File *copy = (File *)[super copyWithZone:zone];
copy.fileSizeString = [[self.fileSizeString copy] autorelease];
//etc etc
return copy;
}
答案 0 :(得分:12)
在File
的{{1}}方法
initWithCoder:
应该是
if ( (self = [super init]) )
答案 1 :(得分:4)
您应该在子类
中调用NSCoding方法的超类实现- (id)initWithCoder:(NSCoder *)coder {
if ( (self = [super initWithCoder:coder]) )
{
self.fileSizeString = [coder decodeObjectForKey:kFileSizeStringKey];
}
return self;
}