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数组, 应该如何编写?

ios

Alien丿鸣 9 years, 2 months ago

推荐 EGOCache

穿的像瓢虫 answered 9 years, 2 months ago

最好的办法是实现归档
看这里吧

如果你懒得读 也没问题
在People中实现两个方法
第一个
-(NSDictionary*)getPeopleDict;
第二个
+(People )getPeopleByDict:(NSDictionary )dict;

方法太简单 你估计懂了
把对象转化为字典
放入数组 然后 arr.writeToFile 就好了
读出数组 调用第二个方法转成你的实例

华丽的笨蛋 answered 9 years, 2 months ago

经过进一步学习, 复杂对象存入数组归档的方法如下:


 - (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

Your Answer