NSUserDefaults(plist)

/* 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/ 要開啟「顯示隱藏檔」的功能才看得到 */

猜你喜欢

转载自cnkira.iteye.com/blog/1820239
今日推荐