NSUserDefaults用来存储类似用户的配置等一些比较小的数据,模拟器/真机保存在沙盒路径的Library——>Preferences文件夹中
一、创建NSUserDefaults对象
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
二、创建NSUserDefaults对象之后即可往里面添加数据,它支持的数据类型有NSString、 NSNumber、NSDate、 NSArray、NSDictionary、BOOL、NSInteger、NSFloat等系统定义的数据类型,如果要存放自定义的对象(如自定义的类对象),则必须将其转换成NSData存储:
NSArray *arr = [[NSArray alloc] initWithObjects:@"arr1", @"arr2", nil]
[userDefaultset setObject:arr forKey:@"arrItem"];
[userDefaultset setObject:@"admin" forKey:@"user_name"];
[userDefaultset BOOL:@YES forKey:@"auto_login"];
[userDefaultset Integer: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 removeObject ForKey:@"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 = [udobject ForKey:@"myBusinessCard"];
// 将NSData转换成对象
bc = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ;