iOS开发中多对象归档操作

1、NSData方式多对象归档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    // 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    // 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]];

3、相关链接

3.1、iOS开发中自定义对象的归档
3.2、iOS开发中基本文件读写操作示例

2 thoughts on “iOS开发中多对象归档操作

  1. Pingback: iOS开发中自定义对象的归档 | 小龙虾博客 (Crayfish)

  2. Pingback: iOS开发中基本文件读写操作示例 | 小龙虾博客 (Crayfish)

Leave a Reply