iPhone - reading and saving preferences [closed]

2019-06-09 15:24发布

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条回答
时光不老,我们不散
2楼-- · 2019-06-09 15:42

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

查看更多
登录 后发表回答