我正在尝试了解NSCoding是如何工作的,但是当我尝试释放以前存档的对象时,似乎遇到了一个问题,这就是我正在做的事情......
// 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"];
问题似乎是上面的最后一行,我想我错了。我的班级看起来像......
@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;
和我的initWithCoder一样......
-(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;
}
任何帮助都会非常感激。
加里
答案 0 :(得分:2)
拨打finishDecoding
后,您无法拨打decodeObjectForKey:
。你显然还没有“完成解码”。完成后请致电finishDecoding
。