-1

I am trying to implement the NSCoder methods encodeWithCoder and initWithCoder for a custom object i have created which has a child array of custom objects. Both custom objects employment the above mentioned methods but after the top level object has been decoded the value for the array is always nil.

Both objects implement the methods below, The dictionary and the arrays or popular from a library i have for getting field names and turning objects into dictionaries. I have checked that encodeObject is being called on the Array and at this time the array is not nil. I have equally checked that the decode method is receiving nil on the other side..

I can't work out where i am going wrong? Am i correct is assuming that so long as child array objects implement the protocol i should be fine to do it this way?

- (void)encodeWithCoder:(NSCoder *)aCoder{
    NSDictionary* dictionary = [jrModelBinder unBind:self];
    for(NSString* field in dictionary)
    {
        id val = [self valueForKey:field];
        [aCoder encodeObject:val forKey:field];
    }
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    if(self = [super init]){
        NSArray* fields = [jrModelBinder propertyNames:self];
        for(NSString* field in fields)
        {
            id val = [aDecoder decodeObjectForKey:field];
            [self setValue:val  forKey:field];
        }
    }
    return self;
}
Jarmez De La Rocha
  • 618
  • 2
  • 9
  • 19

1 Answers1

0

I misunderstood your question before:

NSKeyedArchiver/Unarchiver should encode and decode NSArrays and NSDictionaries with no problem.

But I think since your array itself contains custom Objects which implements below 2 functions:

- (id)initWithCoder:(NSCoder *)aDecoder
- (void)encodeWithCoder:(NSCoder *)enCoder

Try using below for array

NSData * encodedData = [NSKeyedArchiver archivedDataWithRootObject:someArray];

Also use NSKeyedUnarchiver to decode.

bllakjakk
  • 5,045
  • 1
  • 18
  • 28