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

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



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

你可能感兴趣的:(复杂对象存入数组归档的方法如下)