1. NSUserDefaults
//TODO: 1.NSUserDefaults NSUserDefaults类除了可以存储数组、字典、NSdata外,还可以直接存储OC基本类型属性。但是不能直接作用到自定义对象. [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@""];//设置初始值 [[NSUserDefaults standardUserDefaults] synchronize];//进行同步 [[NSUserDefaults standardUserDefaults] objectForKey:@""];//取值
2. Plist
//TODO: 2.Plist文件 //1.根据已有plist文件取值 NSString *pathString = [[NSBundle mainBundle] pathForResource:@"Property List" ofType:@"plist"]; //如果plist文件是一个NSArray,用数组取 NSArray *array = [NSArray arrayWithContentsOfFile:pathString]; //如果plist文件是一个NSDictionary,用字典取 NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:pathString];
//2.创建plist文件 NSArray *homeDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentString = homeDirectory[0]; NSString *documentPath = [documentString stringByAppendingPathComponent:@"GCD.plist"]; NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager createFileAtPath:documentPath contents:nil attributes:nil]; NSArray *fileArray = @[@{@"name":@"one"},@{@"name":@"two"}]; [fileArray writeToFile:documentPath atomically:YES];//写入数据 NSArray *readArray = [NSArray arrayWithContentsOfFile:documentPath];//读取数据
3. 归档、解档
//TODO: 3.归档/解档 archiveModel *model = [[archiveModel alloc]init]; model.name = @"小明"; model.age = @"18"; model.sex = @"男"; NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *filePath = [pathArray[0] stringByAppendingPathComponent:@"model"]; /* 一.只归档一个对象 [NSKeyedArchiver archiveRootObject:model toFile:filePath]; */ /* 一.只解档一个对象 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { //路径存在 archiveModel *readModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; NSLog(@"解档:%@",readModel); } */ //二.归档多个对象 NSMutableData *data = [[NSMutableData alloc]init]; NSKeyedArchiver *keyedArchiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; [keyedArchiver encodeObject:model forKey:@"model"]; //[keyedArchiver encodeObject:model forKey:@"key1"]; //[keyedArchiver encodeObject:model forKey:@"key2"]; [keyedArchiver finishEncoding]; if ([data writeToFile:filePath atomically:YES]) { NSLog(@"归档成功"); } //二.解档多个对象 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSData *data = [NSData dataWithContentsOfFile:filePath]; NSKeyedUnarchiver *keyedUnarchive = [[NSKeyedUnarchiver alloc]initForReadingWithData:data]; archiveModel *readModel = [keyedUnarchive decodeObjectForKey:@"model"]; //archiveModel *readModel = [keyedUnarchive decodeObjectForKey:@"key1"]; //archiveModel *readModel = [keyedUnarchive decodeObjectForKey:@"key2"]; [keyedUnarchive finishDecoding]; }