Using PLists for Persistence on iPhone

前端 未结 2 1239
南方客
南方客 2020-12-17 07: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? I

相关标签:
2条回答
  • 2020-12-17 08:07

    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
    
    0 讨论(0)
  • 2020-12-17 08:19

    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

    0 讨论(0)
提交回复
热议问题