i have a question i created a plist of movies. Root is of type Dictionary and Pixar type Array with 3 string movie titles I am able to read from the list with the following code no problem
NSString *path = [[NSBundle mainBundle] pathForResource:@"Movies" ofType:@"plist"];
NSMutableDictionary *movies =[[NSMutableDictionary alloc] initWithContentsOfFile:path];
from here i can print the list no problem. I want to add another movie to this list now. so i transfered the list to a array and then saved the array back to the file but its not working. any idea of where i went wrong?
NSMutableArray *array= [movies valueForKey:@"Pixar"];
NSString *incredible=@"Incredibles";
[array addObject:incredible];
[movies setObject:array forKey:@"Pixar"];
[movies writeToFile:path atomically:YES];
You cannot, on the device, write to the bundle. The simulator doesn't enforce these constraints, but the device will.
One approach is to:
See if the file exists in the Documents
folder.
If it does, read it from the Documents
folder. If not, read it from the bundle.
When done adding/removing records, write the file to the Documents
folder.
Thus:
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Movies" ofType:@"plist"];
NSString *docsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath = [docsFolder stringByAppendingPathComponent:@"Movies.plist"];
NSMutableDictionary *movies = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsPath])
movies = [NSMutableDictionary dictionaryWithContentsOfFile:documentsPath];
if (!movies)
movies = [NSMutableDictionary dictionaryWithContentsOfFile:bundlePath];
// do whatever edits you want
[movies writeToFile:documentsPath atomically:YES];