Search code examples
iphoneobjective-carraysplist

Increment Number in plist


I am using the method below to get an array from my plist and then increase a certain value by 1, then save it. However I log the array and the value doesn't actually go up each time.

In my plist, I have an array and in that number values, each one is set to 0. So every time I run this again it goes back to 0 it seems.

NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:@"Words.plist"];

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
    NSMutableArray *errors = [dict objectForKey:[NSString stringWithFormat:@"Errors%d.%d", [[stageSelectionTable indexPathForSelectedRow] section] +1, [[stageSelectionTable indexPathForSelectedRow] row] +1]];

    int a = [[errors objectAtIndex:wordIndexPath] intValue];
    a += 1;
    NSNumber *b = [NSNumber numberWithInt:a];
    [errors replaceObjectAtIndex:wordIndexPath withObject:b];

    [errors writeToFile:finalPath atomically:YES];

Solution

  • You can only write to a file in the documents-folder. You can't write to your bundle!

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Namelist.plist"];
    

    You can use NSFilemanager to copy your Plist-File to the documents-folder.


    To get the path of your file:

    - (NSString *)filePath {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyFile.plist"];
        return filePath;
    }
    

    To copy the file if it doesn't exist:

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[self filePath]]) {
            NSString *path = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"plist"];
        [fileManager copyItemAtPath:path toPath:[self filePath] error:nil];
    }
    

    Now you can write your NSDictionary to the Documents-Directory:

    [dict writeToFile:[self filePath] atomically:YES];
    

    But you really need to update the array in the dict!