在自定义类的子类上使用NSCoding [英] Using NSCoding on a subclass of custom class

查看:185
本文介绍了在自定义类的子类上使用NSCoding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSCoding归档/取消归档自定义类作为数据持久性的方法。如果对象是NSObject的子类,它可以正常工作,但我也有自定义对象的子类。我是否需要更改initWithCoder:方法以及encodeWithCoder?现在,特定于子类的属性编码/解码很好,但是子类从超类继承的属性却没有。有什么想法吗?这是基本结构:

I am using NSCoding to archive/unarchive a custom class as a method of data persistence. It works fine if the object is a subclass of NSObject, but I also have objects that are subclasses of custom objects. Do I need to change the initWithCoder: method as well as encodeWithCoder? Right now, the properties that are specific to the subclass encode/decode fine, but properties the subclass inherit from the superclass do not. Any thoughts? Here is the basic structure:

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


推荐答案

<$ c $里面c>文件的 initWithCoder:方法

if ( (self = [super init]) )

应该是

if ( (self = [super initWithCoder:coder]) )

这篇关于在自定义类的子类上使用NSCoding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆