NSUserDefaults (plist) 筆記

今天又看到了一个octopress的Blog  关键是我看到开头的这句话....

科學的愛情
我覺得我這個人最大的缺點就是太他媽的上進了

NSUserDefaults 可以用來儲存使用者的偏好設定(它會被存成一個 .plist 檔案),你可以把它想成是 iOS app 的 localStorage,而且 NSUserDefaults 不只可以儲存字串,還可以儲存任何 Objective-C data type。

// 你得先宣告一個 NSUserDefaults 物件,在同一個 app 裡,它是 singleton(單例)
NSUserDefaults *userPrefs = [NSUserDefaults standardUserDefaults];

// set
[userPrefs setObject:@"a123456789" forKey:@"userID"];
[userPrefs setInteger:24 forKey:@"age"];
[userPrefs setBool:YES forKey:@"isLogin"];

// remove
[userPrefs removeObjectForKey:@"debts"];

[userPrefs synchronize];

// get
NSString *userID = [userPrefs stringForKey:@"userID"];
BOOL isLogin = [userPrefs boolForKey:@"isLogin"];

要注意的是,set 或 remove 之後,記得執行 [userPrefs synchronize],已確保資料被寫入硬碟裡。再保險一點,你還可以:

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */

    [[NSUserDefaults standardUserDefaults] synchronize];
}

如果你是在模擬器上測試,NSUserDefaults 的資料會被儲存在 /Users/[USERNAME]/Library/Application Support/iPhone Simulator/5.1/Applications/[SIMULATOR_APP_ID]/Library/Preferences/[BUNDLE_ID].plist。

/Users/[USERNAME]/Library/ 要開啟「顯示隱藏檔」的功能才看得到,推薦使用 DesktopUtility



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值