NSUserDefault的使用 NSUserDefaults用來存儲類似用戶的配置等一些比較小的數據。 一、創建NSUserDefaults對象 NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; 二、創建NSU ...
NSUserDefault的使用
NSUserDefaults用來存儲類似用戶的配置等一些比較小的數據。
一、創建NSUserDefaults對象
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
二、創建NSUserDefaults對象之後即可往裡面添加數據,它支持的數據類型有NSString、 NSNumber、NSDate、 NSArray、NSDictionary、BOOL、NSInteger、NSFloat等系統定義的數據類型,如果要存放自定義的對象(如自定義的類對象),則必須將其轉換成NSData存儲:
NSArray *arr = [[NSArray alloc] initWithObjects:@"arr1", @"arr2", nil]
[userDefault setObject:arr forKey:@"arrItem"];
[userDefault setObject:@"admin" forKey:@"user_name"];
[userDefault setBOOL:@YES forKey:@"auto_login"];
[userDefault setInteger:1 forKey:@"count"];
三、往NSUserDefaults添加數據後,它們就變成了全局的變數,App中即可讀寫NSUserDefault中的數據:
NSUserDefaults *mySettingDataR = [NSUserDefaults standardUserDefaults];
NSLog(@"arrItem=%@", [mySettingDataR objectForKey:@"arrItem"]);
NSLog(@"user_name=%@", [mySettingDataR objectForKey:@"user_name"]);
NSLog(@"count=%d", [mySettingDataR integerForKey:@"count"]);
四、如果想刪除某個數據項,可以使用removeObjectForKey刪除數據:
[mySettingData removeObjectForKey:@"arrItem"];
五、需要註意的是,NSUserDefaults是定時把緩存中的數據寫入磁碟的,而不是即時寫入,為了防止在寫完NSUserDefaults後程式退出導致的數據丟失,可以在寫入數據後使用synchronize強制立即將數據寫入磁碟:
[mySettingData synchronize];
六、若是寫入自定義類,應該在類實現以下兩個方法
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
// your code
self._firstName = [coder decodeObjectForKey:@"_firstName"];
self._lastName = [coder decodeObjectForKey:@"_lastName"];
}
return self;
}
- (void) encodeWithCoder: (NSCoder *)coder
{
// your code
[coder encodeObject:_firstName forKey:@"_firstName"];
[coder encodeObject:_lastName forKey:@"_lastName"];
}
七、然後再存取時通過NSData做載體:
BusinessCard *bc = [[BusinessCard alloc] init];
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
// 將對象轉換成NSData
NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:bc];
[ud setObject:udObject forKey:@"myBusinessCard"];
udObject = nil;
udObject = [ud objectForKey:@"myBusinessCard"];
// 講NSData轉換成對象
bc = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ;