iOS runtime


runtime是oc的c语言实现
objective c代码编译,先要转变为c语言,然后再进行汇编和编译的操作
将oc转化为c的,就是由runtime实现的。
下面是类、对象、方法、方法列表在c语言中的实现(删除了宏定义部分)

//对象
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};
//类(也叫类对象,类在编译期间用于创建实例的对象,是一个单例,这个结构体中存放的数据称为元数据)
//其中isa指针指向的类叫做元类,通过元类可以创建类对象
//元类的isa指针指向自己
//元类中保存了类方法
struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;
    Class super_class;                                        
    const char *name;                                         
    long version;                                             
    long info;                                                
    long instance_size;                                       
    struct objc_ivar_list *ivars;                             
    struct objc_method_list **methodLists;                    
    struct objc_cache *cache;                                 
    struct objc_protocol_list *protocols;                     
} 
//方法列表
struct objc_method_list {
    struct objc_method_list *obsolete;                        
    int method_count;                                         
    int space;                                                
    struct objc_method method_list[1];                        
}                                                            
//方法
struct objc_method {
    SEL method_name;                                          
    char *method_types;                                       
    IMP method_imp;                                           
}

对象、类、元类之间的关系
在这里插入图片描述

Runtime消息传递

一个对象的方法像这样 [obj foo],编译器转成消息发送 objc_msgSend(obj, foo),Runtime时执行的流程是这样的:

  1. 系统首先找到消息的接收对象,然后通过对象的isa找到它的类。
  2. 在它的类中查找method_list,是否有selector方法。
  3. 没有则查找父类的method_list。
  4. 找到对应的method,执行它的IMP。
  5. 转发IMP的return值。

但是由于一个类中,往往只有少部分方法被调用,因此,objec_class结构体中会使用 objc_cache来缓存常用的方法,以方法名为键,以方法实现为值。

category
struct category_t { 
    const char *name; //所扩展的类的名字
    classref_t cls; 	//所对应的类对象,在编译期是不会指定的,运行时通过name找到类对象
    struct method_list_t *instanceMethods; //实例方法列表
    struct method_list_t *classMethods;	//类方法列表
    struct protocol_list_t *protocols; //协议列表
    struct property_list_t *instanceProperties; //属性(这就是我们可以通过objc_setAssociatedObject和objc_getAssociatedObject增加实例变量的原因,不过这个和一般的实例变量是不一样的。)
};
Runtime消息转发

前文介绍了进行一次发送消息会在相关的类对象中搜索方法列表,如果找不到则会沿着继承树向上一直搜索知道继承树根部(通常为NSObject),如果还是找不到并且消息转发都失败了就回执行 doesNotRecognizeSelector: 方法报unrecognized selector 错。那么消息转发到底是什么呢?接下来将会逐一介绍最后的三次机会(在找不到执行方法后执行)。

  • 动态方法解析
  • 备用接收者
  • 完整消息转发
    在这里插入图片描述
动态方法解析 resolveInstanceMethod

第一次补救机会,让你有机会提供一个函数,如果注册了函数,就会重新启动一次消息转发机制(IMP指针指向的方法具体实现要是c语言函数

- (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(myMethod)];
}


//动态方法解析(这里return YES 或者 NO好像没有影响,只要提供了函数,就会重走一遍消息发送流程)
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    if (sel == @selector(myMethod)) {
        class_addMethod([self class], sel, (IMP)newMethod, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];//返回yes,进入下一步消息转发
}

void newMethod(id obj,SEL name){
    NSLog(@"%@",obj);   //消息发送者
    NSLog(@"%d",name);  //方法标识
    NSLog(@"doing foo");
}

在这里插入图片描述

备用接收者

forwardingTargetForSelector

#import "ViewController.h"
#import "objc/runtime.h"

@interface Person: NSObject

@end

@implementation Person

- (void)foo {
    NSLog(@"Doing foo");//Person的foo函数
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(foo)];
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return YES;//这里只要不给对象添加方法,return yes或no,都会进入下一步
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    if (aSelector == @selector(foo)) {
        return [Person new];//返回Person对象,让Person对象接收这个消息
    }
    return [super forwardingTargetForSelector:aSelector];
}
@end
完整的消息转发

如果在上一步还不能处理未知消息,则唯一能做的就是启用完整的消息转发机制了。
首先它会发送 -methodSignatureForSelector: 消息获得函数的参数和返回值类型。如果 -methodSignatureForSelector: 返回 nilRuntime 则会发出 -doesNotRecognizeSelector: 消息,程序这时也就挂掉了。如果返回了一个函数签名,Runtime就会创建一个 NSInvocation 对象并发送 -forwardInvocation: 消息给目标对象。

#import "ViewController.h"
#import "objc/runtime.h"
@interface Person: NSObject
@end

@implementation Person
- (void)foo {
    NSLog(@"Doing foo");//Person的foo函数
}
@end

@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //执行foo函数
    [self performSelector:@selector(foo)];
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return YES;//返回YES,进入下一步转发
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
    return nil;//返回nil,进入下一步转发
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if ([NSStringFromSelector(aSelector) isEqualToString:@"foo"]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];//签名,进入forwardInvocation
    }
    return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    SEL sel = anInvocation.selector;

    Person *p = [Person new];
    if([p respondsToSelector:sel]) {
        [anInvocation invokeWithTarget:p];
    }
    else {
        [self doesNotRecognizeSelector:sel];
    }
}
@end

runtime的一些使用

1:给category增加属性
#import "ViewController.h"
#import "objc/runtime.h"

@interface UIView (DefaultColor)

@property (nonatomic, strong) UIColor *defaultColor;

@end

@implementation UIView (DefaultColor)

@dynamic defaultColor;

static char kDefaultColorKey;

- (void)setDefaultColor:(UIColor *)defaultColor {
	//添加set方法
	//参数 1:操作的目标对象 2:属性的唯一标识 3:属性内容 4:管理策略,这里是 nonatomic和retain。
    objc_setAssociatedObject(self, &kDefaultColorKey, defaultColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)defaultColor {
    //添加get方法
    //通过唯一标识取出方法
    return objc_getAssociatedObject(self, &kDefaultColorKey);
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIView *test = [UIView new];
    test.defaultColor = [UIColor blackColor];
    NSLog(@"%@", test.defaultColor);
}

@end
添加方法、方法替换、KVO实现

添加方法

//1:要添加到的对象
//2:要添加的方法对应的sel
//3:要添加的方法的具体实现
//4:类型编码
class_addMethod([self class], sel, (IMP)fooMethod, "v@:");

方法替换,这里替换了 viewDidLoad方法

@implementation ViewController

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        SEL originalSelector = @selector(viewDidLoad);
        SEL swizzledSelector = @selector(jkviewDidLoad);
        
        Method originalMethod = class_getInstanceMethod(class,originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class,swizzledSelector);
        
        //judge the method named  swizzledMethod is already existed.
        BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        // if swizzledMethod is already existed.
        if (didAddMethod) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        }
        else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (void)jkviewDidLoad {
    NSLog(@"替换的方法");
    
    [self jkviewDidLoad];
}

- (void)viewDidLoad {
    NSLog(@"自带的方法");
    
    [super viewDidLoad];
}

@end

swizzling 应该只在 +load 中完成。 在 Objective-C 的运行时中,每个类有两个方法都会自动调用。+load 是在一个类被初始装载时调用,+initialize 是在应用第一次调用该类的类方法或实例方法前调用的。两个方法都是可选的,并且只有在方法被实现的情况下才会被调用。
swizzling 应该只在 dispatch_once 中完成,由于swizzling 改变了全局的状态,所以我们需要确保每个预防措施在运行时都是可用的。原子操作就是这样一个用于确保代码只会被执行一次的预防措施,就算是在不同的线程中也能确保代码只执行一次。Grand Central Dispatch 的 dispatch_once满足了所需要的需求,并且应该被当做使用swizzling 的初始化单例方法的标准。
实现图解如下:
在这里插入图片描述

kvo实现

KVO的实现依赖于 Objective-C 强大的 Runtime,当观察某对象 A 时,KVO 机制动态创建一个对象A当前类的子类,并为这个新的子类重写了被观察属性 keyPath 的 setter 方法。setter 方法随后负责通知观察对象属性的改变状况。
Apple 使用了 isa-swizzling 来实现 KVO 。当观察对象A时,KVO机制动态创建一个新的名为:NSKVONotifying_A的新类,该类继承自对象A的本类,且 KVO 为 NSKVONotifying_A 重写观察属性的 setter 方法,setter 方法会负责在调用原 setter 方法之前和之后,通知所有观察对象属性值的更改情况。

NSKVONotifying_A 类剖析

NSLog(@"self->isa:%@",self->isa);  
NSLog(@"self class:%@",[self class]);  

在建立KVO监听前,打印结果为:

self->isa:A
self class:A

在建立KVO监听之后,打印结果为:

 self->isa:NSKVONotifying_A
 self class:A

在这个过程,被观察对象的 isa 指针从指向原来的 A 类,被KVO 机制修改为指向系统新创建的子类 NSKVONotifying_A 类,来实现当前类属性值改变的监听;
所以当我们从应用层面上看来,完全没有意识到有新的类出现,这是系统“隐瞒”了对 KVO 的底层实现过程,让我们误以为还是原来的类。但是此时如果我们创建一个新的名为 NSKVONotifying_A 的类,就会发现系统运行到注册 KVO 的那段代码时程序就崩溃,因为系统在注册监听的时候动态创建了名为 NSKVONotifying_A 的中间类,并指向这个中间类了。

- (void)setName:(NSString *)newName { 
      [self willChangeValueForKey:@"name"];    //KVO 在调用存取方法之前总调用 
      [super setValue:newName forKey:@"name"]; //调用父类的存取方法 
      [self didChangeValueForKey:@"name"];     //KVO 在调用存取方法之后总调用
}
实现NSCoding的自动归档和自动解档

有时候对象的属性太多,归档和解档可能会不大方便,这时候使用kvo就能方便的归档和解档:

(id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        unsigned int outCount;
        Ivar * ivars = class_copyIvarList([self class], &outCount);
        for (int i = 0; i < outCount; i ++) {
            Ivar ivar = ivars[i];
            NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    unsigned int outCount;
    Ivar * ivars = class_copyIvarList([self class], &outCount);
    for (int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}
实现字典和模型的自动转换
- (instancetype)initWithDict:(NSDictionary *)dict {

    if (self = [self init]) {
        //(1)获取类的属性及属性对应的类型
        NSMutableArray * keys = [NSMutableArray array];
        NSMutableArray * attributes = [NSMutableArray array];
        /*
         * 例子
         * name = value3 attribute = T@"NSString",C,N,V_value3
         * name = value4 attribute = T^i,N,V_value4
         */
        unsigned int outCount;
        objc_property_t * properties = class_copyPropertyList([self class], &outCount);
        for (int i = 0; i < outCount; i ++) {
            objc_property_t property = properties[i];
            //通过property_getName函数获得属性的名字
            NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            [keys addObject:propertyName];
            //通过property_getAttributes函数可以获得属性的名字和@encode编码
            NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
            [attributes addObject:propertyAttribute];
        }
        //立即释放properties指向的内存
        free(properties);

        //(2)根据类型给属性赋值
        for (NSString * key in keys) {
            if ([dict valueForKey:key] == nil) continue;
            [self setValue:[dict valueForKey:key] forKey:key];
        }
    }
    return self;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值