Search code examples
objective-cloadsavearchivenscoding

Objective-C: How to make it save two files instead of one for NSCoding?


My code is here:

-(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"];
}

It works if I save a file once with a specified fileKey (i.e: "buttons").. BUT then if I want to save another file to disk with a specified fileKey (i.e: "clocks"), it would overwrite "buttons" with "clocks", so "buttons cannot be accessed again..

How to fix this dilemma? I believe it should be how I "saveDataToDisk" (archive), I should be writing a bunch of files to disk, instead of replacing each one by the most current one.


Solution

  • Unless I am reading your code wrong, you are always using the same path to save the file to. That is why it is overwriting.

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

    Every time you save the file is at /path/you/retrieve/data.bin

    You need to change the filename, or, the directory that it is saved in. If you want to keep the same filename then make a new directory every time you save and just label the directory with a time stamp or a description of what you are saving.