iPhone - reading and saving preferences [closed]

喜欢而已 提交于 2019-12-08 09:54:38

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/5391286/iphone-reading-and-saving-preferences

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