Runtime-原理与应用

2017-08-21  本文已影响3人  攻克乃还_
使用运行时前提,必须导入#import <objc/message.h>

1.runtime使用技巧

2.1.对象如何找到对应方法去调用:

1.根据isa指针找到所属类
2.根据方法编号在方法列表中找到类中的方法名
3.根据方法名到方法区找到方法的实现

2.2.类如何找到类方法去调用:

1.根据所属类的isa指针找到元类
2.根据方法编号在类方法列表中找到类中的方法名
3.根据方法名到方法区找到方法的实现
4.如果没有,向父元类查找实现

3.消息机制

    Person *p = [[Person alloc] init];
    //不带参数 
    objc_msgSend(p, @selector(eat));
    //带参数
    objc_msgSend(p, @selector(eat), 20);

4.交换方法

    + (void)load
    {
    Method imageNamedMethod = class_getClassMethod(self,   @selector(imageNamed:));
    // 获取xmg_imageNamed
    Method xmg_imageNamedMethod = class_getClassMethod(self,     @selector(xmg_imageNamed:));
    // 交互方法:runtimec
    method_exchangeImplementations(imageNamedMethod,    xmg_imageNamedMethod);
    }

5.添加方法

#import "ViewController.h"
#import "Person.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    Person *p = [[Person alloc] init];
    [p performSelector:@selector(eat)];
    [p performSelector:@selector(run:) withObject:@1];
}
@end

#import "Person.h"
#import <objc/message.h>

@implementation Person

+ (BOOL)resolveInstanceMethod:(SEL)sel{

    if(sel == NSSelectorFromString(@"eat")){
        class_addMethod(self, sel, (IMP)eat, "v@:@");
        return YES;
    }
    if(sel == NSSelectorFromString(@"run:")){
        class_addMethod(self, sel, (IMP)(run), "v@:@");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

void eat(id self, SEL _cmd){
    NSLog(@"吃了吗您那?");
}

void run(id self, SEL _cmd, NSNumber *num){
    NSLog(@"跑了%@米", num);
}
@end

6.添加属性:

@interface NSObject (Property)
@property NSString *name;
@end

- (void)setName:(NSString *)name{
objc_setAssociatedObject(self, @"name", name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)name{
return objc_getAssociatedObject(self, @"name");
}
上一篇下一篇

猜你喜欢

热点阅读