fuzzygoat
fuzzygoat

Reputation: 26223

Problem using decodeObjectForKey?

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

Upvotes: 0

Views: 928

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

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.

Upvotes: 2

Related Questions