runtime学习笔记

####一、runtime简介

  • RunTime简称运行时。OC就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制。
  • 对于C语言,函数的调用在编译的时候会决定调用哪个函数。
  • 对于OC的函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。
  • 事实证明:
    • 在编译阶段,OC可以调用任何函数,即使这个函数并未实现,只要声明过就不会报错。
    • 在编译阶段,C语言调用未实现的函数就会报错。 #目录:
  • 交换两个方法
  • IMP指针的使用
  • 动态添加方法
  • 给分类添加属性

#####1.交换两个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+ (void)load{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method viewDidLoad = class_getInstanceMethod(self, @selector(viewDidLoad));
        Method viewDidLoaded = class_getInstanceMethod(self, @selector(viewDidLoaded));
        method_exchangeImplementations(viewDidLoad, viewDidLoaded);
    });
    
}

- (void)viewDidLoaded {

    NSLog(@"helloviewDidLoaded");
}

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"helloviewDidLoad");
}

实例:交换imageNamed:方法实现没有图片时给出相应提示;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#import <UIKit/UIKit.h>
@interface UIImage (image)
+ (instancetype)imageWithName:(NSString *)name;
@end

#import "UIImage+imageName.h"
#import <objc/runtime.h>
@implementation UIImage (image)
+ (void)load
{
    // 交换方法
    // 获取imageWithName方法地址
    Method imageWithName = class_getClassMethod(self, @selector(imageWithName:));
    // 获取imageWithName方法地址
    Method imageName = class_getClassMethod(self, @selector(imageNamed:));
    // 交换方法地址,相当于交换实现方式
    method_exchangeImplementations(imageWithName, imageName);
}

// 不能在分类中重写系统方法imageNamed,因为会把系统的功能给覆盖掉,而且分类中不能调用super.
// 既能加载图片又能打印
+ (instancetype)imageWithName:(NSString *)name
{
    // 这里调用imageWithName,相当于调用imageName
    UIImage *image = [self imageWithName:name];
    if (image == nil) {
        NSLog(@"加载空的图片");
    }
    return image;
}
@end

1
2
3
4
5
6
7
8
9
- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *image = [UIImage imageNamed:@"111"];
    UIImageView *imagView = [UIImageView new];
    imagView.frame = [UIScreen mainScreen].bounds;
    imagView.contentMode = UIViewContentModeScaleAspectFit;
    [imagView setImage:image];
    [self.view addSubview:imagView];
}

#####2.IMP指针的使用

还有一个地方我们需要注意,如果这样直接调用IMP的话就会发生经典的EXC_BAD_ACCESS错误,我们定义的IMP指针是一个有返回值的类型,而其实我们获取的viewDidLoad这个方法是没有返回值的,所以我们需要新定义一个和IMP相同类型的函数指针比如VIMP,把他的返回值定位Void,**这样如果你修改的方法有返回值就用IMP,没有返回值就用VIMP。**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
typedef id(*_VIMP) (id,SEL,...);
typedef void(*_IMP) (id,SEL,...);

@implementation UIViewController

+ (void)load{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method viewDidLoad = class_getInstanceMethod(self, @selector(viewDidLoad));
      _IMP viewDidLoad_IMP = (_IMP)method_getImplementation(viewDidLoad);
     
      method_setImplementation(viewDidLoad, imp_implementationWithBlock(^(id target, SEL action){
       
            viewDidLoad_IMP(target,@selector(action));
            NSLog(@"%@",target);
       
        }));
    });
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"helloviewDidLoad");
    
}

实际上 直接调用一个方法的IMP指针的效率是高于调用方法本身的所以,如果你有一个合适的时机获取到方法的IMP的话,你可以试着调用它。

#####3.动态添加方法

  • 开发使用场景:如果一个类方法非常多,加载类到内存的时候也比较* 耗费资源,需要给每个方法生成映射表,可以使用动态给某个类,添加方法解决。
  • 经典面试题:有没有使用performSelector,其实主要想问你有没有动态添加过方法。
  • 简单使用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @implementation ViewController
    -(void)viewDidLoad {
        [super viewDidLoad];

      Person *p = [Person new];
        
        if ([p respondsToSelector:@selector(eat)]){
            // 默认person,没有实现eat方法,可以通过performSelector调用,但是会报错。
            // 动态添加方法就不会报错
            [p performSelector:@selector(eat)];
        }
    }
    @end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@implementation Person
// void(*)()
// 默认方法都有两个隐式参数,
void eat(id self,SEL sel)
{
    NSLog(@"%@ %@",self,NSStringFromSelector(sel));
}
// 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来.
// 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法
+(BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(eat)) {
        // 动态添加eat方法
        // 第一个参数:给哪个类添加方法
        // 第二个参数:添加方法的方法编号
        // 第三个参数:添加方法的函数实现(函数地址)
        // 第四个参数:函数的类型,(返回值+参数类型) v:void @:对象->self :表示SEL->_cmd
        class_addMethod(self, @selector(eat), eat, "v@:");
    }
    return [super resolveInstanceMethod:sel];
}
@end

#####4. 给分类添加属性

  • 原理:给一个类声明属性,其实本质就是给这个类添加关联,并不是直接把这个值的内存空间添加到类存空间。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 给系统NSObject类动态添加属性name
    
    NSObject *objc = [[NSObject alloc] init];
    objc.name = @"小码哥";
    NSLog(@"%@",objc.name);
    
}
@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 定义关联的key
static const char *key = "name";

@implementation NSObject (Property)

- (NSString *)name
{
    // 根据关联的key,获取关联的值。
    return objc_getAssociatedObject(self, key);
}

- (void)setName:(NSString *)name
{
    // 第一个参数:给哪个对象添加关联
    // 第二个参数:关联的key,通过这个key获取
    // 第三个参数:关联的value
    // 第四个参数:关联的策略
    objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

附上runtimeDemo