2011-12-13 5 views
0

だから、どうやらここに私のコード..私は指定されたfileKeyで一度ファイルを保存する場合目的C:NSCodingの代わりに2つのファイルをどのように保存できるかについての助けがありますか?

-(void)loadDataFromDisk 
{ 
    [dict release]; 
    NSMutableData* data = [NSMutableData dataWithContentsOfFile:[self pathForDataFile]]; 
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 
    dict = [[unarchiver decodeObjectForKey:fileKey] retain]; 
    [unarchiver finishDecoding]; 
    [unarchiver release]; 

    if(dict == NULL) 
    { 
    NSLog(@"First time in."); 
    dict = [[NSMutableDictionary alloc] init]; 
    } 
} 

-(void)saveDataToDisk 
{ 
    NSMutableData* data = [NSMutableData data]; 
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 

    [archiver setOutputFormat:NSPropertyListBinaryFormat_v1_0]; 

    // EncodeObject will automatically encode every primitive inside 'dictionaryToSave', 
    // As for objects, the object class must conform to NSCoding Protocol, else an error will occur. 
    [archiver encodeObject:dict forKey:fileKey]; 
    [archiver finishEncoding]; 
    [archiver release]; 

    [data writeToFile:[self pathForDataFile] atomically:YES];  
} 

-(NSString*)pathForDataFile 
{ 
    NSArray* documentDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 

    NSString* path = nil; 
    if (documentDir) 
    { 
     path = [documentDir objectAtIndex:0];  
    } 
    else 
    { 
     NSLog(@"error in [PersistentHandler pathForDataFile]"); 
    } 
    // Returns 'directory'/data.bin to method(saveDatatoDisk/loadDataFromDisk) 
    return [NSString stringWithFormat:@"%@/%@", path, @"data.bin"]; 
    } 

それは動作します(例:「ボタン」)..しかし、私はしてディスクに別のファイルを保存したい場合は"clocks"で "buttons"を上書きするので、 "ボタンに再びアクセスすることはできません。

誰かがこれを修正する方法を知っていますか? saveDataToDisk "(アーカイブ)、私はディスクにファイルの束を書いているはずですが、各ディスクを最新のものに置き換えるのではなく、誰でもこのジレンマで助けてくれると大変感謝しています。

答えて

1

あなたのコードが間違っていない限り、ファイルを保存するために常に同じパスを使用しています。それが上書きされている理由です。

return [NSString stringWithFormat:@"%@/%@", path, @"data.bin"]; 

たびにファイルを保存するには、あなたは、ファイル名、または、それが保存されているディレクトリを変更する必要が

/path/you/retrieve/data.binである。あなたがしたい場合は同じファイル名にしておき、保存するたびに新しいディレクトリを作成し、タイムスタンプや保存しているものの説明でディレクトリにラベルを付けるだけです。

+0

ありがとうございました。 –

1

あなたは常に "〜/ Documents/data.bin"に書き込みます。pathForDataFileメソッドは常にそのパスを返します。別のファイルに保存する場合は、別のファイルに書き込む必要があります。

関連する問題