编码与NSKeyedArchiver NSMutableArray部分Encode NSMutableArray partially with NSKeyedArchiver

- 此内容更新于:2015-01-27
主题:

原文:

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?

rmaddy的回复:这# 39;子类NSMutableArray年代不是一个好主意。# 39;实质性的年代的一部分“类cluster"。子类不能# 39;没有理由了。只是存档/ unarchive整个NSMutableArray。

(原文:It's not a good idea to subclass NSMutableArray. It's part of a "class cluster". And there's no reason to subclass it anyway for this. Just archive/unarchive the whole NSMutableArray.)

解决方案:
你可以子类人PartialPerson,您可以存档/ unarchive。 子类NSMutableArray这不是一个好主意,我认为没有理由这样做。
原文:

You can subclass Person into PartialPerson, which you can archive/unarchive.

It's not a good idea to subclass NSMutableArray, and I see no reason for doing so.

Den Ob的回复:嗯. .我不明白它会帮助我。我有一个NSMutableArray与一些人。我看到太多的唯一方法# 39;年代创建一个部分NSMutableArray并保存它的副本。但它需要额外的内存复制人实体(?)。

(原文:Hmm.. I dont understand how it will help for me. I have a NSMutableArray with some Persons. The only way I see it's create a partial copy of NSMutableArray and save it. But it needs additional RAM to duplicate Person entities (or not?).)