使用runtime机制实现属性的赋值

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    

    NSLog(@"%s",__func__);

    unsigned int count =  0;

    Class cls = self.class;

    Ivar * varList = NULL;

    objc_property_t * proList = NULL;

    while (cls!=[NSObject class])

    {

         BOOL isSelfClass = (cls == self.class);

        if(isSelfClass)

        {

           varList = class_copyIvarList(cls, &count);

            

        }else

        {

          proList = class_copyPropertyList(cls, &count);

        }

        for (int i = 0; i < count; i++)

        {

            const char * name =  isSelfClass?ivar_getName(varList[i]):property_getName(proList[i]);

            NSString * key = [NSString stringWithFormat:@"%s",name];

            NSArray * filters = @[@"superclass", @"description", @"debugDescription", @"hash"];

            if ([self valueForKey:key] && [filters containsObject:key] == NO) {

                [aCoder encodeObject:[self valueForKey:key] forKey:key];

            }

            

        }

        if(varList==NULL)

        {

             free(varList);

            varList = NULL;

        }else if (proList==NULL)

        {

            free(proList);

            proList = NULL;

            

        }

        cls = class_getSuperclass(cls);

        

    }

    

}

 

posted @ 2017-03-01 15:41  tiankongzhicheng  阅读(187)  评论(0编辑  收藏  举报