Josh Kahane
Josh Kahane

Reputation: 17169

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];

Upvotes: 0

Views: 121

Answers (2)

Fabio Poloni
Fabio Poloni

Reputation: 8371

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!

Upvotes: 4

Evan Mulawski
Evan Mulawski

Reputation: 55334

You are writing the array to disk, instead of the dictionary that the array originated from:

[dict writeToFile:finalPath atomically:YES];

Also, you will need to replace the Errors%d.%d object with the updated one before saving it:

[dict setObject:errors forKey:/* your formatted key*/];

Finally, as @mavrick3 pointed out, you cannot save files to your bundle, only to your application's documents directory.

Upvotes: 2

Related Questions