Using NSCoding in a Custom Class Subclass

I use NSCoding to archive / unzip a custom class as a method of storing data. 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 the encodeWithCoder? Right now, subclass-specific properties encode / decode in order, but properties that inherit the subclass for the superclass do not. Any suggestions? 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 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; } 
+6
source share
2 answers

Inside the File initWithCoder:

 if ( (self = [super init]) ) 

it should be

 if ( (self = [super initWithCoder:coder]) ) 
+11
source

You must 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; } 
+4
source

Source: https://habr.com/ru/post/900141/


All Articles