美文网首页
OC获取类的属性和变量

OC获取类的属性和变量

作者: 东旭39 | 来源:发表于2020-09-29 20:57 被阅读0次

    定义一个类

    @interface LGPerson : NSObject
    {
        NSString *hobby;
        NSObject *objc;
    }
    @property (nonatomic, copy) NSString *nickName;
    @property (nonatomic, strong) NSString *name;
    @end
    @implementation LGPerson
    @end
    
    void lgObjc_copyIvar_copyProperies(Class pClass){
        
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList(pClass, &count);
        for (unsigned int i=0; i < count; i++) {
            Ivar const ivar = ivars[i];
            //获取实例变量名
            const char*cName = ivar_getName(ivar);
            NSString *ivarName = [NSString stringWithUTF8String:cName];
            LGLog(@"class_copyIvarList:%@",ivarName);
        }
        free(ivars);
    
        unsigned int pCount = 0;
        objc_property_t *properties = class_copyPropertyList(pClass, &pCount);
        for (unsigned int i=0; i < pCount; i++) {
            objc_property_t const property = properties[i];
            //获取属性名
            NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
            //获取属性值
            LGLog(@"class_copyProperiesList:%@",propertyName);
        }
        free(properties);
    }
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
             LGPerson *person = [LGPerson alloc];
             Class pClass     = object_getClass(person);
    
            lgObjc_copyIvar_copyProperies(pClass);
            NSLog(@"Hello, World!");
        }
        return 0;
    }
    
    

    输出

    class_copyIvarList:hobby
    class_copyIvarList:objc
    class_copyIvarList:_nickName
    class_copyIvarList:_name
    class_copyProperiesList:nickName
    class_copyProperiesList:name
    

    相关文章

      网友评论

          本文标题:OC获取类的属性和变量

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