Using NSCoding on a subclass of custom class

≡放荡痞女 提交于 2019-12-07 02:00:59

问题


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

and the subclass:

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

回答1:


Inside the File's initWithCoder: method

if ( (self = [super init]) )

should be

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



回答2:


You should call the superclass implementation of the NSCoding methods in your subclass

- (id)initWithCoder:(NSCoder *)coder {
    if ( (self = [super initWithCoder:coder]) )
    {
        self.fileSizeString = [coder decodeObjectForKey:kFileSizeStringKey];
    }
    return self;
}


来源:https://stackoverflow.com/questions/7904298/using-nscoding-on-a-subclass-of-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!