Using PLists for Persistence on iPhone

試著忘記壹切 提交于 2019-11-27 22:49:16

问题


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



来源:https://stackoverflow.com/questions/6885997/using-plists-for-persistence-on-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!