NSUserDefaults
是一個(gè)使用非常頻繁的持久化存儲(chǔ)方式俄周,使用過程中可能會(huì)遇到的兩個(gè)問題:
- key容易寫錯(cuò)導(dǎo)致無法存儲(chǔ)或讀取失敗崎弃。
我們隊(duì)NSUserDefaults
新建分類NSUserDefaults+XYW
想括,然后在這個(gè)分類里儡陨,對(duì)偏好設(shè)置進(jìn)行處理司致,對(duì)外只暴露讀和取的方法煞躬,不用關(guān)心key是什么肛鹏,和進(jìn)行偏好設(shè)置的時(shí)候需要做什么。
@implementation NSUserDefaults (XYW)
#pragma mark - launchTimes
static NSString *const nightModelKey = @"nightModelKey";
-(BOOL)isNightModel{
return [[NSUserDefaults standardUserDefaults] boolForKey:nightModelKey];
}
-(void)setNightModel:(BOOL)night{
[[NSUserDefaults standardUserDefaults] setBool:night forKey:nightModelKey];
if (night) {
//改變偏好設(shè)置的時(shí)候恩沛,可以做一些其他的事情
[[NSNotificationCenter defaultCenter] postNotificationName:nightModelKey object:@(night)];
}
}
@end
- 不能及時(shí)同步導(dǎo)致的存儲(chǔ)失敗在扰。
NSUserDefaults
為了速度和性能,默認(rèn)只改變內(nèi)存中的數(shù)據(jù)雷客,而不是實(shí)時(shí)同步到本地文件健田。所以使用時(shí)有可能會(huì)出現(xiàn)偏好設(shè)置為存儲(chǔ)到本地的情況。如果一些很重要的設(shè)置佛纫,希望立刻同步到本地妓局,可以在設(shè)置完后手動(dòng)調(diào)用[[NSUserDefaults standardUserDefaults] synchronize];
立刻同步到本地,當(dāng)然此操作如果過于頻繁將會(huì)影響性能呈宇。如何避免“非重要”設(shè)置未能及時(shí)同步到本地呢好爬?我們來幫app選一個(gè)合適的時(shí)機(jī),比如APP終止甥啄,APP失活的時(shí)候存炮,手動(dòng)同步一下。雖然不知道系統(tǒng)是否已經(jīng)做了這件事蜈漓,自己再做一遍終究更放心穆桂。
//停止
-(void)applicationWillTerminate:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] synchronize];
}
// 失活
-(void)applicationWillResignActive:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] synchronize];
}