一、用户偏好设置的存取:
1、写:
//偏好设置存储
NSUserDefaults * userDefauls = [NSUserDefaults standardUserDefaults];
//设置数据
[userDefauls setObject:@"Jack" forKey:@"name"];
[userDefauls setObject:@"11111111111" forKey:@"phone"];
[userDefauls setBool:YES forKey:@"isAutoLogin"];
//立即存储
[userDefauls synchronize];
2、读:
//读取偏好设置
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//读取数据
NSString * name = [userDefaults objectForKey:@"name"];
NSString * phone = [userDefaults objectForKey:@"phone"];
BOOL isAuto = [userDefaults boolForKey:@"isAutoLogin"];
NSLog(@"%@---%@ --- %d",name,phone,isAuto);
二、数组的存储(NSDictionary 的存储类似)
1、写
//1.构建数据
NSArray * names = @[@"小明",@"AngleBaby",@"bob",@"Jack"];
//2.获取documents路径,存到主目录中
NSString * docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
//3.拼接文件名
NSString * fileName = [docDir stringByAppendingPathComponent:@"names.txt"];
//4.存储
//参数2:是否原子型写入
[names writeToFile:fileName atomically:YES];
2、读
//获取documents路径
NSString * docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
//拼接文件名
NSString * fileName = [docDir stringByAppendingPathComponent:@"names.txt"];
NSArray * names = [NSArray arrayWithContentsOfFile:fileName];
NSLog(@"%@",names);
三、字典的存储
1、写
//1.构建数据
NSDictionary *person = @{
@"name":@"jack",
@"sex":@"male",
@"student":@[@"lemon",@"mega"]
};
//2.获取documents路径
NSString * docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//3.拼接文件名
NSString * fileName = [docDir stringByAppendingPathComponent:@"teacher.plist"];
//4.存储
//参数2:是否原子型写入
[person writeToFile:fileName atomically:YES];
NSLog(@"%@",fileName);
2、读
//获取documents路径
NSString * docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//拼接文件名
NSString * fileName = [docDir stringByAppendingPathComponent:@"teacher.plist"];
NSDictionary * teacher = [NSDictionary dictionaryWithContentsOfFile:fileName];
NSLog(@"%@",teacher);
四、自定义对象的存储
1、写
//创建模型类的对象
HMContact * contact = [[HMContact alloc] init];
contact.name = @"JackMeng";
contact.phone = @"18610988888";
//获取documents文件夹
NSString * docuDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
//拼接文件名
NSString * fileName= [docuDir stringByAppendingPathComponent:@"contact"];
//归档
[NSKeyedArchiver archiveRootObject:contact toFile:fileName];
2、读
//获取documents文件夹
NSString * docuDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
//拼接文件名
NSString * fileName= [docuDir stringByAppendingPathComponent:@"contact"];
//反归档
HMContact * contact = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName];
NSLog(@"%@ --- %@",contact.name,contact.phone);