TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
1、NSData方式多对象归档- // 1、创建归档路径
- NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"data.plist"];
- // 2、创建可变数据对象
- NSMutableData *data = [NSMutableData data];
- // 3、创建归档
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
- // 4、归档中添加对象元素
- [archiver encodeObject:array forKey:@"array"];
- [archiver encodeObject:dict forKey:@"dict"];
- [archiver encodeObject:string forKey:@"string"];
- [archiver encodeObject:imageData forKey:@"image"];
- // 5、结束归档
- [archiver finishEncoding];
- // 6、写入本地沙盒
- [data writeToFile:dataPath atomically:YES];
- // 7、取出归档即解档
- NSData *data1 = [NSData dataWithContentsOfFile:dataPath];
- NSKeyedUnarchiver *unarchive1 = [[NSKeyedUnarchiver alloc] initForReadingWithData:data1];
- // 8、还原各对象
- NSArray *array1 = [unarchive1 decodeObjectForKey:@"array"];
- NSDictionary *dict1 = [unarchive1 decodeObjectForKey:@"dict"];
- NSString *string1 = [unarchive1 decodeObjectForKey:@"string"];
- UIImage *imag1 = [UIImage imageWithData:[unarchive1 decodeObjectForKey:@"image"]];
复制代码 2、数组方式进行多对象归档- // 1、创建归档路径
- NSString *dataPath2 = [documentsPath stringByAppendingPathComponent:@"data.array"];
- // 2、创建多对象数组
- NSArray *arrayArchiver = @[array, dict, string, imageData];
- // 3、归档数组
- [NSKeyedArchiver archiveRootObject:arrayArchiver toFile:dataPath2];
- // [arrayArchiver writeToFile:dataPath2 atomically:YES];
- // 4、取出归档即解档
- NSArray *getArray2 = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath2];
- //NSArray *getArray1 = [NSArray arrayWithContentsOfFile:dataPath2];
- // 5、还原数组中各对象
- NSArray *array2 = getArray2[0];
- NSDictionary *dict2 = getArray2[1];
- NSString *string2 = getArray2[2];
- UIImage *image2 = [UIImage imageWithData:getArray2[3]];
复制代码 基本归档操作请参考:http://www.yusian.com/bbs/thread-7979-1-1.html |
|