iOS 如何归档一个Model数组
self.title = @"复杂对象归档";
Person *personA = [[Person alloc] init];
personA.name = @"张三";
personA.age = 20;
personA.sex = @"男";
Person *personB = [[Person alloc] init];
personB.name = @"李四";
personB.age = 15;
personB.sex = @"女";
Person *personC = [[Person alloc] init];
personC.name = @"王五";
personC.age = 30;
personC.sex = @"男";
NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"Caches: %@", paths);
NSMutableArray *personsArr = [NSMutableArray arrayWithObjects:personA, personB, personC, nil];
NSString *personsArrPath = [paths stringByAppendingString:@"/personsArr.plist"];
[personsArr writeToFile:personsArrPath atomically:YES];
NSLog(@"%@", personsArrPath);
代码如上, 我想要归档一个Model数组, 应该如何编写?
Alien丿鸣
9 years, 2 months ago
Answers
经过进一步学习, 复杂对象存入数组归档的方法如下:
- (void)complexObjectArchiver
{
Person *personA = [[Person alloc] init];
personA.name = @"张三";
personA.age = 20;
personA.sex = @"男";
Person *personB = [[Person alloc] init];
personB.name = @"李四";
personB.age = 15;
personB.sex = @"女";
Person *personC = [[Person alloc] init];
personC.name = @"王五";
personC.age = 30;
personC.sex = @"男";
NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"Caches: %@", paths);
NSMutableArray *personsArr = [NSMutableArray arrayWithObjects:personA, personB, personC, nil];
NSString *personsArrPath = [paths stringByAppendingString:@"/personsArr.plist"];
[NSKeyedArchiver archiveRootObject:personsArr toFile:personsArrPath];
NSLog(@"personsArrPath: %@", personsArrPath);
NSArray *newPersonsArr = [NSKeyedUnarchiver unarchiveObjectWithFile:personsArrPath];
NSLog(@"反归档: %@", newPersonsArr);
for (Person *tempPerson in newPersonsArr) {
NSLog(@"name: %@, age: %ld, sex: %@", tempPerson.name, tempPerson.age, tempPerson.sex);
}
}
即, 先将复杂对象存入数组, 再将数组按照复杂对象归档的方式写入本地; 反之亦然.
LV9900
answered 9 years, 2 months ago