OC获取类的属性和变量

2020-09-29  本文已影响0人  东旭39

定义一个类

@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
上一篇下一篇

猜你喜欢

热点阅读