I have my Person class which implements NSCoding protocol:
@interface Person : NSObject <NSCoding>
@property NSString *name;
@property float salary;
@end
@implementation Person
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeFloat:_salary forKey:@"salary"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if(self=[super init])
{
_name =[aDecoder decodeObjectForKey:@"name"];
_salary=[aDecoder decodeFloatForKey:@"salary"];
}
return self;
}
Also I have an array with persons, which I want to serialize. But not all the entities. I want to save it partially. I decided to create my own subclass of NSMutableArray which will implement NSCoding protocol and it's own encodeWithCoder and initWithCoder methods:
@interface customNSMutableArray : NSMutableArray<NSCoding>
@end
@implementation customNSMutableArray
-(void)encodeWithCoder:(NSCoder *)aCoder
{
for(NSObject * obj in self)
{
//if(some_condition)
[aCoder encodeObject:obj];
}
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
//@todo
return self;
}
@end
And here is a trouble. After trying to encode my customNSMutableArray:
@property customNSMutableArray *companyStaff;
...
NSData * data=[NSKeyedArchiver archivedDataWithRootObject:_companyStaff];
The encodeWithCoder method in my customNSMutableArray is not invoked. It's directly passed to encodeWithCoder of my Person entities within the array.
How can I serialize NSMutableArray partially?
NSMutableArray. It's part of a "class cluster". And there's no reason to subclass it anyway for this. Just archive/unarchive the wholeNSMutableArray. - rmaddy