获取类的属性列表、方法列表、实例变量列表

 unsigned int ivarCount = 0;
    Ivar *ivars = class_copyIvarList([User class], &ivarCount);
    
    for (unsigned int i = 0; i < ivarCount; i++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        NSLog(@"ivar name = %@", [NSString stringWithUTF8String:name]);
        
        ptrdiff_t offset = ivar_getOffset(ivar);
        NSLog(@"ivar offset = %zd", offset);
        
        const char *encoding = ivar_getTypeEncoding(ivar);
        NSLog(@"ivar type = %@", [NSString stringWithUTF8String:encoding]);
    }
    free(ivars);
    
    unsigned int methodCount = 0;
    Method *methods = class_copyMethodList([User class], &methodCount);
    
    for (unsigned int i = 0; i < methodCount; i++) {
        Method method = methods[i];
        
        SEL sel = method_getName(method);
        NSLog(@"method name = %@", NSStringFromSelector(sel));
        
        char *returnType = method_copyReturnType(method);
        NSLog(@"method returnType = %@", [NSString stringWithUTF8String:returnType]);
        free(returnType);
        
        const char *typeEncoding = method_getTypeEncoding(method);
        NSLog(@"method typeEncoding = %@", [NSString stringWithUTF8String:typeEncoding]);
        
        unsigned int argumentCount = method_getNumberOfArguments(method);
        for (unsigned int i = 0; i < argumentCount; i++) {
            char *argumentType = method_copyArgumentType(method, i);
            NSLog(@"method argumentType = %@", [NSString stringWithUTF8String:argumentType]);
            free(argumentType);
        }
    }
    free(methods);
    
    unsigned int propertyCount = 0;
    objc_property_t *propertys = class_copyPropertyList([User class], &propertyCount);
    
    for (unsigned int i = 0; i < propertyCount; i++) {
        objc_property_t property = propertys[i];
        
        const char *name = property_getName(property);
        NSLog(@"property name = %@", [NSString stringWithUTF8String:name]);
        
        unsigned int attCount = 0;
        objc_property_attribute_t *attributes = property_copyAttributeList(property, &attCount);
        for (unsigned int i = 0; i < attCount; i++) {
            objc_property_attribute_t att = attributes[i];
            NSLog(@"attribute name = %@", [NSString stringWithUTF8String:att.name]);
            NSLog(@"attribute value = %@", [NSString stringWithUTF8String:att.value]);
        }
        free(attributes);
    }
    free(propertys);

猜你喜欢

转载自my.oschina.net/mexiaobai1315/blog/1806766