2010-03-16 15 views
1

EDIT_002:進一步重寫:如果我使用下面的方法保存,該方法如何將其加載回去看看? (月亮是NSNumbers的一個NSMutableArray)如何使用encodeWithCoder保存後加載對象?

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

-(void)saveMoons:(NSString *)savePath { 
    NSMutableData *data = [[NSMutableData alloc] init]; 
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 
    [moons encodeWithCoder:archiver]; 
    [archiver finishEncoding]; 
    [data writeToFile:savePath atomically:YES]; 

    [archiver release]; 
    [data release]; 
} 

加里

+1

你現在有什麼問題?就個人而言,我更喜歡你的簡單版本。做非簡單版本的唯一原因是如果你必須對對象做特別的事情(或者創建一個非標準的文件格式)。 –

+0

簡單的一個適合我需要的東西,我只是感興趣。我可能有一個想法,我做錯了什麼,我會快速查看,並編輯我發現的... – fuzzygoat

+0

是的,我能看到的唯一的問題是1)如果月亮不是財產或不是保留財產;或2)如果loadPath在某種程度上是不正確的路徑(即,與savePath不同)。 –

回答

1

發現了它,我的問題是,我是用...

[moons encodeWithCoder:archiver]; 

我應該使用已...

[archiver encodeObject:moons]; 

因此,裝載機會是什麼樣子:

-(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