美文网首页
runtime归档接档(保存模型)

runtime归档接档(保存模型)

作者: 又又轻 | 来源:发表于2018-08-03 14:23 被阅读12次
    - (instancetype)initWithCoder:(NSCoder *)aDecoder{
    //-(instancetype)initWithCoder:(NSCoder *)aDecoder{
        
       self = [super init];
        if (self) {
            unsigned int count = 0;
            Ivar *varList = class_copyIvarList([self class], &count);
            for (int i =0; i<count; i++) {
                
                Ivar var = varList[i];
                const char *varName =   ivar_getName(var);
                NSString *varNameString = [NSString stringWithUTF8String:varName];
                id value = [aDecoder decodeObjectForKey:varNameString];
                
                [self setValue:value forKey:varNameString];
                
            }
            
            free(varList);
            
            
        }
        
        return self;
    }
    - (void)encodeWithCoder:(NSCoder *)aCoder;
    //-(void)encoderWithCoder:(NSCoder *)aCoder
    {
        
        unsigned int count = 0;
        Ivar *varList = class_copyIvarList([self class], &count);
        for (int i =0; i<count; i++) {
            
            Ivar var = varList[i];
            const char *varName =   ivar_getName(var);
            NSString *varNameString = [NSString stringWithUTF8String:varName];
            id value = [self valueForKey:varNameString];
            
            [aCoder encodeObject:value forKey:varNameString];
            
        }
        
        free(varList);
        
    }
    
       Person *p = [[Person alloc]init];
        p.name = @"武带";
        p.age = 24;
        p.sex = 1;
        
        
        
        NSString *temp = NSTemporaryDirectory();
        NSString *fileTemp = [temp stringByAppendingString:@"person.archive"];
        [NSKeyedArchiver archiveRootObject:p toFile:fileTemp];
        
    
        
        id data1 =  [NSKeyedUnarchiver unarchiveObjectWithFile:fileTemp];

    相关文章

      网友评论

          本文标题:runtime归档接档(保存模型)

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