美文网首页
复杂对象存入数组归档的方法如下

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

作者: GrayMantis | 来源:发表于2017-07-18 13:28 被阅读0次

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

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

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/csxhkxtx.html