开发者

How to load object after saving with encodeWithCoder?

开发者 https://www.devze.com 2022-12-22 22:43 出处:网络
EDIT_002: Further rewrite: if I save using the method below how would the method to load it back in look? (moons is an NSMutableArray of NSNumbers)

EDIT_002: Further rewrite: if I save using the method below how would the method to load it back in look? (moons is an NSMutableArray of NSNumbers)

// ------------------------------------------------------------------- **
// METHOD_002
// ------------------------------------------------------------------- **

-(void)saveMoons:(NSString *)savePath {
    NSMutableData *data = [[NSMutableDa开发者_Go百科ta alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [moons encodeWithCoder:archiver];
    [archiver finishEncoding];
    [data writeToFile:savePath atomically:YES];

    [archiver release];
    [data release];
}

gary


Found it, my problem was that I was using ...

[moons encodeWithCoder:archiver];

where I should have been using ...

[archiver encodeObject:moons];

Hence the loader would look like:

-(void)loadMoons_V3:(NSString *)loadPath {
    NSData *data = [[NSData alloc] initWithContentsOfFile:loadPath];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    [self setMoons:[unarchiver decodeObject]];
    [unarchiver finishDecoding];

    [unarchiver release];
    [data release];
}

gary

0

精彩评论

暂无评论...
验证码 换一张
取 消