复杂对象存入数组归档的方法如下

复杂对象存入数组归档的方法如下:



- (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);
    }
}

注意: model对象 首先要实现 归档和解档方法
例子:

model为:
@property (nonatomic,copy) NSString *id;
@property (nonatomic,copy) NSString *name;


//归档

- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    [aCoder encodeObject:self.id forKey:@"id"];
    [aCoder encodeObject:self.name forKey:@"name"];
  }

//解档

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]){
        self.id = [aDecoder decodeObjectForKey:@"id"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
        
    }
    return self;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容