我花了一些时间查看 iPhone 文档和多个帖子。如果您不想在“设置”应用程序中为您的应用程序创建设置,我认为以下内容足以满足大多数目的。
这是一个代码 sn-p,您可以将其放入 AppDelegate didFinishLaunching:
NSString *test = @"Test";
NSString *testKey = @"TestKey";
NSString *test2 = @"Test2";
NSString *test2Key = @"Test2Key";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:test,testKey,test2,test2Key,nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dict];
/*
Alternative if we want to create default values in a file called Defaults.plist in Resources folder
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];
To set the preference within the app:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"MyNewTest" forKey:@"TestKey"];
To retrieve the preference within the app:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *results = [defaults stringForKey:@"TestKey"];
Can also use the following syntax:
intForKey:
floatForKey:
boolForKey:
objectForKey:
Returns Objective-C object like NSString, NDDate, or NSNumber
If the object is not a string, may need to specify the value, such as
Label.text = [[defaults objectForKey:@"TestPreferenceStoredAsNumber"]stringValue];
*/
在 AppDelegate applicationWillTerminate 和 applicationDidEnterBackground 中放置以下内容:
[[NSUserDefaults standardUserDefaults]synchronize];
然后查看首选项,将此代码放在方便的位置:
// View all keys and values in Console
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);