I am getting comfortable with using plists for initializing my app. I now want to save app state back to the plist used to initialize the app and I find myself stuck. At application startup I ingest the plist into an NSDictionary which is immutable. I now want to update the NSDictionary by replacing old values with new values for existing keys and write to the plist via [NSDictionary writeToFile:atom开发者_C百科ically]. How do I get around the immutability of NSDictionary?
Thanks, Doug
UPDATE - Not quite there yet
I followed zneak's suggestion and ingested my settings file into an NSMutableDictionary. Works fine. Prior to writing the plist out I confirm that new values now replace old values. Cool. Good to go.
Problem: when I write the file thusly:
if ([self.settings writeToFile:plistPath atomically:YES] == NO) {
NSLog(@"Unable to write plist");
}
The method happily completes properly - the conditional is YES rather then NO - but I see no file. Where has the file gone?
Shouldn't I see the new file in my directory tree?
Make it a NSMutableDictionary
by calling -[myDict mutableCopy]
, then use this one for writing the file; or simply load the plist using [NSMutableDictionary dictionaryWithContentsOfFile:(NSString*)]
to get a mutable instance to start with instead of an immutable one.
Use an NSMutableDictionary
(you can use -[NSDictionary mutableCopy]
to create it). You can then use writeToFile
just as with an NSDictionary
.
精彩评论