iOS - runtime - getProperty - getIvar - getMethod - getprotocol

场景:通过传一个viewcontroller给一个第三方的sdk进行操作,但是想知道这个第三方sdk中点击了按钮会发生什么,如何获取到这个controller 传过去之后他们的controller的类名,通过viewController.presentedViewController可以得到present之后的controller的类名

const char *className = object_getClassName(viewController.presentedViewController);
    NSString *cName = [NSString stringWithFormat:@"%s",className];
    NSLog(@"GDT playerController------%@",cName);
    [runtimeTest getProperties:cName];
    [runtimeTest getIvar:cName];

 

iOS 中的runtime可以获取一个类的所有属性,成员变量,方法,协议等

通过获取到方法名,项目中可以直接通过selector 去调用第三方的方法,实现我们直接调用第三方api无法实现的方法

//属性
+(void)getProperties:(NSString*)className {
    u_int count = 0;
    objc_property_t *properties = class_copyPropertyList(NSClassFromString(className), &count);
    
    for (int i = 0; i < count; i++) {
        const char *propertyName = property_getName(properties[i]);
        const char *attributes = property_getAttributes(properties[i]);
        NSString *str = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
        NSString *attributesStr = [NSString stringWithCString:attributes encoding:NSUTF8StringEncoding];
        NSLog(@"propertyName : %@", str);
        NSLog(@"attributesStr : %@", attributesStr);
    }
    free(properties);
}
//成员变量
+(void)getIvar:(NSString*)className {
    u_int count = 0;
    Ivar *ivarList = class_copyIvarList(NSClassFromString(className), &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivarList[i];
        const char *ivarName = ivar_getName(ivar);
        NSLog(@"ivar name -:%@",[NSString stringWithUTF8String:ivarName]);
    }
    free(ivarList);
}
//方法
+(void)printMethodList:(NSString*)className {
    u_int count;
    Method *methodList = class_copyMethodList(NSClassFromString(className), &count);
    for (unsigned int i = 0; i < count; i++) {
        Method method = methodList[i];
        NSLog(@"method(%d) : %@", i, NSStringFromSelector(method_getName(method)));
    }
    free(methodList);
}
//协议
+(void)printProtocolList:(NSString*)className {
    u_int count;
    __unsafe_unretained Protocol **protocolList = class_copyProtocolList(NSClassFromString(className), &count);
    for (unsigned int i = 0; i < count; i++) {
        Protocol *myProtocal = protocolList[i];
        const char *protocolName = protocol_getName(myProtocal);
        NSLog(@"protocol(%d) : %@", i, [NSString stringWithUTF8String:protocolName]);
    }
    free(protocolList);
}

 

 

 

这个T,和N,V是什么意思呢?

T:当前属性的数据结构

N:nonatomic

V:属性名,同我们

@property (nonatomic , strong) UIButton *pushBtn;

即:_pushBtn

 

 

 

 

posted @ 2019-11-28 16:49  lemon小虎  阅读(212)  评论(0)    收藏  举报