iOS runtime 笔记二 — Method 介绍及 swi

2016-09-10  本文已影响205人  黑羽肃霜

参考内容

Objective-C Runtime 运行时之三:方法与消息

方法中 SEL, IMP, Method 的定义与关系

![示意图](https://img.haomeiwen.com/i1180547/f7906aa5b8893729.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

SEL

SEL sel = @selector(methodName);
NSLog(@"address = %p",sel);// log输出为 address = 0x100002d72
-(void)setWidth:(int)width;
-(void)setWidth:(double)width;

IMP

id (*IMP)(id, SEL, ...)

个人理解:

Method


Method 方法及说明

// 添加方法
BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types );

// 获取实例方法
Method class_getInstanceMethod ( Class cls, SEL name );

// 获取类方法
Method class_getClassMethod ( Class cls, SEL name );

// 获取所有方法的数组
Method * class_copyMethodList ( Class cls, unsigned int *outCount );

// 替代方法的实现
IMP class_replaceMethod ( Class cls, SEL name, IMP imp, const char *types );

// 返回方法的具体实现
IMP class_getMethodImplementation ( Class cls, SEL name );
IMP class_getMethodImplementation_stret ( Class cls, SEL name );

// 类实例是否响应指定的selector
BOOL class_respondsToSelector ( Class cls, SEL sel );

说明

示例,实现 method swizzle

用runtime + category 实现

注释.png

runtimetypes的说明

const char *types一个定义该函数返回值类型和参数类型的字符串
举例说明

BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
class_addMethod([TestClass class], @selector(ocMethod:), (IMP)testFunc, "i@:@");
* `i`表示方法的返回类型,下面是`dash`中的截图
函数说明.png
* 第一个@是必须有的,表示self. 也就是说,上面说的返回类型+@是必备的。
* :@ 表示传入的参数。如果有两个参数,就是:@@.可参见下面的代码
BOOL class_addMethod(Class cls,SEL name,IMP imp,    const char *types)   

/**
  * 一个参数
  *
  */

int cfunction(id self, SEL _cmd, NSString *str) {
    NSLog(@"%@", str);
    return10;//随便返回个值
}

-(void) oneParam {  
    TestClass *instance = [[TestClassalloc]init];
    //    方法添加
    class_addMethod([TestClassclass],@selector(ocMethod:), (IMP)cfunction,"i@:@");
    
    if ([instance respondsToSelector:@selector(ocMethod:)]) {
        NSLog(@"Yes, instance respondsToSelector:@selector(ocMethod:)");
    } else
        NSLog(@"Sorry");
    
    int a = (int)[instance ocMethod:@"我是一个OC的method,C函数实现"];
    NSLog(@"a:%d", a);
}

 /**
  * 两个参数
  *
  */

int cfunctionA(id self, SEL _cmd, NSString *str, NSString *str1) {
    NSLog(@"%@-%@", str, str1);
    return20;//随便返回个值
}
-(void) twoParam {  
    TestClass *instance = [[TestClass alloc]init];   
    class_addMethod([TestClass class],@selector(ocMethodA::), (IMP)cfunctionA,"i@:@@");
    
    if ([instance respondsToSelector:@selector(ocMethodA::)]) {
        NSLog(@"Yes, instance respondsToSelector:@selector(ocMethodA::)");
    } else
        NSLog(@"Sorry");
    int a = (int)[instance ocMethodA:@"我是一个OC的method,C函数实现" :@"-----我是第二个参数"];
    NSLog(@"a:%d", a);
}
上一篇 下一篇

猜你喜欢

热点阅读