简介
NSUserDefaults是一个单例,在整个程序中只有一个实例对象,他可以用于数据的永久保存,而且简单实用。适合存储轻量级的本地数据。
支持的数据类型:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL
注意:对相同的Key赋值约等于一次覆盖,故要保证每一个Key的唯一性
存取简单数据到本地
- 取
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
NSData *data = [userD objectForKey:@"UUID"];
- 存
[userD setObject:uuidString forKey:@"UUID"];
[userD synchronize]; //同步,确保保存成功
存取图片
- 存
UIImage *img3;
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(img3) forKey:@"sharePic3"];
[[NSUserDefaults standardUserDefaults] synchronize];
- 取
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
NSData* imageData = [userD objectForKey:@"sharePic1"];
UIImage *img = [UIImage imageWithData:imageData];
存取字典
存取的字典对象都必须是不可变的
-存
// 新增的字典
NSDictionary *dicAdd = @{@"key" : @"value"};
// 添加
[cur_dict addEntriesFromDictionary:dicAdd];
// 先化为不可变字典,再保存
NSDictionary *fdict =[[NSDictionary alloc] initWithDictionary:cur_dict];
[[NSUserDefaults standardUserDefaults] setObject:fdict forKey:@"Adict"];
-取
// 取出
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"Adict"];
// 化为可变字典 进行后续操作
NSMutableDictionary *cur_dict = [[NSMutableDictionary alloc] initWithCapacity:0];
[cur_dict addEntriesFromDictionary:dict];
存取数组
存取的数组对象都必须是不可变的
- 存
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"123",@"234", nil];
// 先转换为不可变 数组
NSArray * array = [NSArray arrayWithArray:mutableArray];
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[user setObject:array forKey:@"names"];
- 取
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
NSArray *arr = [userD arrayForKey:@"names"];
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:arr];