转自: http://blog.csdn.net/totogogo/article/details/7473851
NSUserDefaults用于存储一些app setting。当你关闭app之后再打开后,之前存储的setting依然可以从NSUserDefaults里读取。注意:密码最好不要存储在NSUserDefaults里,要存储也必须用AES/DES加密存储,更安全的方法是 https://github.com/ldandersen/scifihifi-iphone
把密码存储在NSUserDefault or plist里的后果: http://www.shushao.com/news/info/item/203510-ios
example 1: 读取NSUserDefaults里的"color" setting
example 2: 写入NSUserDefaults里的"color" setting为"red"
[[NSUserDefaults standardUserDefaults] setObject:@"red" forKey:@"color"];
另外NSUserDefaults还提供了一个registerDefaults方法,通常在appDelegate的didFinishLaunchingWithOptions里调用
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
registerDefaults方法调用时会check NSUserDefaults里是否已经存在了相同的key,如果有则不会把其覆盖。举个例子:
1 当第一次run上面的app时,"color"="blue"会写入NSUserDefaults里
2 然后你的app调用了
[[NSUserDefaults standardUserDefaults] setObject:@"red" forKey:@"color"];
这时NSUserDefaults里"color"="red"
3. exit app and restart it,registerDefaults方法还是会被调用,但它check到"color" key已经存在,就不会把它写入NSUserDefaults中
这时NSUserDefaults里"color"="red"
4. 修改registerDefaults方法变成
然后重新run app,之后NSUserDefaults里依然"color"="red"
5. 修改registerDefaults方法变成
然后重新run app,之后NSUserDefaults里依然"color"="red",不过多了a pair of key-value: username=tomson
注意:
* If you terminate your app by pressing "Stop" in Xcode (in the Simulator or on the device), your User Defaults might get saved
* 我没试过NSUserDefaults在exit app之后被保存,有人说碰到,并给出代码调用""的解决方案
ref links:
http://stackoverflow.com/questions/6033385/nsuserdefaults-not-being-saved-in-simulator
http://stackoverflow.com/questions/2622754/why-is-nsuserdefaults-not-saving-my-values