使用偏好設(shè)置存儲數(shù)據(jù)

iOS應(yīng)用支持偏好設(shè)置,要來保存數(shù)據(jù),比如保存用戶名、密碼、字體大小等設(shè)置,iOS提供了一套標(biāo)準(zhǔn)的解決方案來為應(yīng)用加入偏好設(shè)置。

     每個應(yīng)用都有一個NSUserDefaults實例,通過它來存取偏好設(shè)置。

+ (NSUserDefaults *)standardUserDefaults //單例對象

存儲偏好設(shè)置使用set開頭的方法,如:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"aaa" forKey:@"account"];
[defaults setObject:@"123" forKey:@"password"];
[defaults setInteger:10 forKey:@"age"];
[defaults setBool:YES forKey:@"autoLogin"];
//存儲后立刻同步
[defaults synchronize];

讀取偏好設(shè)置也有對應(yīng)的方法,如:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSString * account = [defaults objectForKey:@"account"];
BOOL autoLogin  = [defaults boolForKey:@"autoLogin"];

  • 應(yīng)用案例:新特性頁面的顯示

很多App下載或更新后第一次打開會顯示一個新特性頁面(往往是多張圖片展示新特性),再次打開不會再顯示。

實現(xiàn)方式:

    將每一次App運(yùn)行時的版本號存儲在偏好設(shè)置中

    App啟動時,檢測存儲在偏好設(shè)置中的版本號與當(dāng)前的版本號是否一致

如:

//AppDelegate的didFinishLaunching...方法中

//通過UserDefault獲得上一次app運(yùn)行時的版本
NSString * lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:UserDefaultBundleVerson];
//獲取當(dāng)前Bundle Version
NSURL * infoPlistURL = [[NSBundle mainBundle] URLForResource:@"Info.plist" withExtension:nil];
NSDictionary * dict = [NSDictionary dictionaryWithContentsOfURL:infoPlistURL];
NSString * currentVersion = dict[(NSString*)kCFBundleVersionKey];
//如果這個版本時第一次進(jìn)入,則顯示新特性頁面
if ( ![currentVersion isEqualToString:lastVersion] ) {
    UIViewController * vc = [[UIStoryboard storyboardWithName:@"MainPage" bundle:nil] instantiateViewControllerWithIdentifier:@"newFeature"];
    self.window.rootViewController = vc;
}
else {
    UIViewController * vc = [[UIStoryboard storyboardWithName:@"MainPage" bundle:nil] instantiateViewControllerWithIdentifier:@"mainPage"];
    self.window.rootViewController = vc;
}
//新特性跳轉(zhuǎn)到App主頁時

//獲取當(dāng)前Bundle Version
NSURL * infoPlistURL = [[NSBundle mainBundle] URLForResource:@"Info.plist" withExtension:nil];
NSDictionary * dict = [NSDictionary dictionaryWithContentsOfURL:infoPlistURL];
NSString * currentVersion = dict[(NSString*)kCFBundleVersionKey];
//將當(dāng)前版本保存到UserDefault中
[[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:UserDefaultBundleVerson];

標(biāo)題名稱:使用偏好設(shè)置存儲數(shù)據(jù)
網(wǎng)頁路徑:http://muchs.cn/article2/pieooc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、關(guān)鍵詞優(yōu)化、Google、動態(tài)網(wǎng)站、網(wǎng)站排名建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管