Using PLists for Persistence on iPhone

2019-01-25 00:39发布

问题:

Simple question about property lists within an iphone app. I know you can read data in from a plist, but is there a way to write user-inputted data to a plist? If so, how? It's easy to find tutorials on reading information from plists, but I'm having trouble finding resources on writing to plists.

回答1:

This is how I write data items to a plist:

[myPlistFile setInteger: myInt forKey: @"someKey"];

Of course, you can change setInteger with setBool, etc for different types.

Hope this helps!

--

Edit:

If your .plist was a member of an important class or similar...

Header of myClass:

NSUserDefaults* myPreferences;
@property (nonatomic, retain) NSUserDefaults* myPreferences;

.m of myClass:

self.myPreferences = [NSUserDefaults standardUserDefaults]; // load our preferences
[[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle]pathForResource: @"nameOfFile" ofType: @"plist"]]]; // now load the custom .plist file


回答2:

In the docs for both NSArray and NSDictionary it shows they each have an instance method:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

For NSDictionary it describes this method as

Writes a property list representation of the contents of the dictionary to a given path.

For NSArray it says this in the discussion

This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

So essentially both of these will write plist's if the items that they contain can be used in plists e.g. Array, Dictionary, Boolean, Data, Date, Number and String