runtime-API-method

1.获取方法

Method method = class_getInstanceMethod(NSPerson.class, @selector(run));

2.获取方法名

    SEL method_name =  method_getName(method);
    NSLog(@"method_name:%@",NSStringFromSelector(method_name));

3.获取方法编码

    const char * method_type = method_getTypeEncoding(method);
    NSLog(@"method_type:%s",method_type);

4.获取方法实现

  • class_getMethodImplementation //更快
  • method_getImplementation
    IMP method_imp = method_getImplementation(method);
    NSLog(@"method_imp:%p",method_imp);

    //faster than method_getImplementation
    IMP run_imp_0 = class_getMethodImplementation(NSPerson.class, @selector(run));
    NSLog(@"run_imp_0:%p",run_imp_0);

5.获取方法参数个数

    unsigned int method_arguments = method_getNumberOfArguments(method);
    NSLog(@"method_arguments:%d",method_arguments);

6.拷贝方法返回类型

    char *method_return_type = method_copyReturnType(method);
    NSLog(@"method_return_type:%s",method_return_type);
    free(method_return_type);

7.拷贝指定参数类型

    char *method_arg_type_0 = method_copyArgumentType(method, 0);
    char *method_arg_type_1 = method_copyArgumentType(method, 1);
    
    NSLog(@"method_arg_type_0->%s",method_arg_type_0);
    NSLog(@"method_arg_type_1->%s",method_arg_type_1);
    free(method_arg_type_0);
    free(method_arg_type_1);

8.获取返回类型

    char dst[8] = {};
    method_getReturnType(method, dst, 8);
    
    NSLog(@"dst:%s",dst);
    
    for (int i = 0; i < 8; i ++) {
        NSLog(@"%c",dst[i]);
    }

9.获取指定参数类型

    char arg_dst_0[8] = {};
    char arg_dst_1[8] = {};

    method_getArgumentType(method, 0, arg_dst_0, 8);
    method_getArgumentType(method, 1, arg_dst_1, 8);
    
    NSLog(@"arg_dst_0->%s",arg_dst_0);
    NSLog(@"arg_dst_1->%s",arg_dst_1);

10.获取方法描述

    struct objc_method_description *description = method_getDescription(method);
    NSLog(@"name:%@",NSStringFromSelector(description->name));
    NSLog(@"types:%s",description->types);

11.给方法设置实现

    IMP run_imp_1 = method_setImplementation(method, (IMP)travel_add);
    NSLog(@"run_imp:%p",run_imp_1);
    [NSPerson.new run];

12.方法交换


    //see NSMutableArray+extension
    
    NSMutableArray *m_arr = [NSMutableArray array];
    [m_arr addObject:nil];
    [m_arr addObject:@"a"];
    [m_arr addObject:@"v"];
    NSLog(@"%@",m_arr);

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容