I am having head ache for a few hours trying to get to write some info to plist file.
My plist looks like this:
<plist version="1.0">
<array>
<dict>
<key>page</key>
<string>page 1</string>
<key>description</key>
<string>description text 1</string>
</dict>
<dict>
<key>page</key>
<string>page 2</string>
<key>description</key>
<string>description text 2</string>
</dict>
</array>
</plist>
I just want to write a new entry to plist like
page
3
description
description text 3
this is the code I use
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"bookmark.plist"]; //
NSMutableDictionary *rootArray = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[rootArray setObject:@"Jimmy1" forKey:@"page"];
[rootArray setObject:@"Jimmy2" forKey:@"description"];
[rootArray writeToFile:path atomically:YES];
when I run I do not get any error message but just doest write anything to bookmark.plist, could you give me an idea on how to solve this problem?
thanks
I believe your problem is you have an array of dicts not a root dictionary. So when you init your
NSMutableDictionaryyou’re actually getting an array.I think you need to init an
NSMutableArray, add a new dictionary as the object that has the objects you want. then write your array to file.Haven’t checked this in Xcode but I think this is the root of your problem.
Update
Definitely check out Rahul‘s answer. He remembered to wrap the write method in an if statement. This is definitely best practice for error handling.