views:

52

answers:

1

I am trying to learn how NSCoding works, but seem to have come accross an issue when I try and unachive a previously archived object, this is what I am doing ...

// CREATE EARTH & ADD MOON
Planet *newPlanet_002 = [[Planet alloc] init];
[newPlanet_002 setName:@"Earth"];
[newPlanet_002 setType:@"Terrestrial Planet"];
[newPlanet_002 setMass:[NSNumber numberWithInt:1]];
[newPlanet_002 addMoon:[moonsOfEarth objectAtIndex:0]];

// ARCHIVE PLANET OBJECTS (Save)
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:newPlanet_002 forKey:@"EARTH"];
[archiver finishEncoding];

BOOL success = [data writeToFile:PathName atomically:YES];
if(success == YES) NSLog(@"Write: OK");
[archiver release];
[data release];

// UNARCHIVE PLANET EARTH (Load)
NSData *dataStore = [[NSData alloc] initWithContentsOfFile:PathName];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:dataStore];
[unarchiver finishDecoding];

Planet *savedPlanet = [unarchiver decodeObjectForKey:@"EARTH"];

The problem seems to be the last line above, which I guess I am getting wrong. My class looks like ...

@interface Planet : NSObject <NSCoding>
{
    NSString *name;
    NSString *type;
    NSNumber *mass;
    NSMutableArray *moons;
}
@property(retain, nonatomic) NSString *name;
@property(retain, nonatomic) NSString *type;
@property(retain, nonatomic) NSNumber *mass;
@property(retain, nonatomic) NSMutableArray *moons;

and my initWithCoder like this ...

-(id)initWithCoder:(NSCoder *)aDecoder {
    NSLog(@"_initWithCoder:");
    self = [super init];
    if(self) {
        [self setName:[aDecoder decodeObjectForKey:@"NAME"]];
        [self setType:[aDecoder decodeObjectForKey:@"TYPE"]];
        [self setMass:[aDecoder decodeObjectForKey:@"MASS"]];
        [self setMoons:[aDecoder decodeObjectForKey:@"MOONS"]];
    }
    return self;
}

any help would be much appreciated.

gary

+2  A: 

Once you've called finishDecoding, you can't then call decodeObjectForKey:. You obviously haven't "finished decoding" yet. You call finishDecoding when you're done.

Rob Napier
Thank you Rob, sorry silly mistake, I sort of had it in my head that the decoding was the actual setting up the NSData object and then you assign it to an object, a bit like the encode where you finishEncoding and then write to disk. Much appreciated.
fuzzygoat