开发者

iPhone - reading and saving preferences [closed]

开发者 https://www.devze.com 2023-02-18 19:24 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discuss开发者_如何学Goion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 9 years ago.

I've read the Apple doc about Preferences but this is still a little bit complex for me to understand. I have an application with a custom screen for setting the Preferences, and I'd like just the code to manage the read and write stuff.

Would you know a detailed tutorial (not writen years ago) or a project sample code somewhere I could read to understand ?


You should use NSUserDefaults :

You set it like that:

       NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

then you can set new objects like that:

   [defaults setBool:YES forKey:@"bools"];
   [defaults setObject:[NSNumber numberWithInt:14] forKey:@"numbers"];
   [defaults setFloat:60.0 forKey:@"floats"];
   [defaults setObject:@"simple string" forKey:@"strings"];
   [defaults setObject:[NSDate date]  forKey:@"dates"];

when you need to read a value you can use :

   NSUInteger integerFromPrefs = [defaults integerForKey:@"integers"];
   BOOL boolFromPrefs = [defaults boolForKey:@"bools"];
       NSString *stringFromPrefs = [defaults objectForKey:@"bools"];
       etc...

and remember to synchronize your changes after each change:

   [defaults synchronize];

BTW

You can read and write to the NSUserDefaults from any view in your application.

Edit

To see all of the data in the NSUserDefaults you can use:

  NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

This will print all the keys and values stored in the plist.

GOOD LUCK

0

精彩评论

暂无评论...
验证码 换一张
取 消