技术

iOS的Runtime讲解与使用

2018-03-27  本文已影响2人  萧修

一、Runtime简介

object-c是基于C语言加入了面向对象特性和消息转发机制的动态语言,除编译器之外,还需用Runtime系统来动态创建类和对象,进行消息发送和转发。

二、Runtime数据结构

在Objective-C中,使用[receiver message]语法并不会马上执行receiver对象的message方法的代码,而是向receiver发送一条message消息,这条消息可能由receiver来处理,也可能由转发给其他对象来处理,也有可能假装没有接收到这条消息而没有处理。其实[receiver message]被编译器转化为:

id objc_msgSend ( id self, SEL op, ... );

下面从两个数据结构id和SEL来逐步分析和理解Runtime有哪些重要的数据结构。

SEL

SEL是函数objc_msgSend第二个参数的数据类型,表示方法选择器,按下面路径打开objc.h文件

typedef struct objc_selector *SEL;

其实它就是映射到方法的C字符串,你可以通过Objc编译器命令@selector()或者Runtime系统的sel_registerName函数来获取一个SEL类型的方法选择器。如果你知道selector对应的方法名是什么,可以通过NSString* NSStringFromSelector(SEL aSelector)方法将SEL转化为字符串,再用NSLog打印。

id

接下来看objc_msgSend第一个参数的数据类型id,id是通用类型指针,能够表示任何对象。按下面路径打开objc.h文件:

/// Represents an instance of a class.

struct objc_object {

    Class isa  OBJC_ISA_AVAILABILITY;

};

/// A pointer to an instance of a class.

typedef struct objc_object *id;

id其实就是一个指向objc_object结构体指针,它包含一个Class isa成员,根据isa指针就可以顺藤摸瓜找到对象所属的类。

Class

isa指针的数据类型是Class,Class表示对象所属的类,按下面路径打开objc.h文件:

可以查看到Class其实就是一个objc_class结构体指针,但这个头文件找不到它的定义,需要在runtime.h才能找到objc_class结构体的定义。

isa表示一个Class对象的Class,也就是Meta Class。在面向对象设计中,一切都是对象,Class在设计中本身也是一个对象。我们会在objc-runtime-new.h文件找到证据,发现objc_class有以下定义:

struct objc_class : objc_object {

  // Class ISA;

  Class superclass;

  cache_t cache;            // formerly cache pointer and vtable

  class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags

  ......

}

由此可见,结构体objc_class也是继承objc_object,说明Class在设计中本身也是一个对象。

其实Meta Class也是一个Class,那么它也跟其他Class一样有自己的isa和super_class指针,关系如下:

super_class表示实例对象对应的父类;

name表示类名;

ivars表示多个成员变量,它指向objc_ivar_list结构体。在runtime.h可以看到它的定义:

objc_ivar_list

其实就是一个链表,存储多个objc_ivar,而objc_ivar结构体存储类的单个成员变量信息。

methodLists

表示方法列表,它指向objc_method_list结构体的二级指针,可以动态修改*methodLists的值来添加成员方法,也是Category实现原理,同样也解释Category不能添加属性的原因。在runtime.h可以看到它的定义:

同理,objc_method_list也是一个链表,存储多个objc_method,而objc_method结构体存储类的某个方法的信息。

cache用来缓存经常访问的方法,它指向objc_cache结构体,后面会重点讲到。

protocols表示类遵循哪些协议。

Method表示类中的某个方法,在runtime.h文件中找到它的定义:

其实Method就是一个指向objc_method结构体指针,它存储了方法名(method_name)、方法类型(method_types)和方法实现(method_imp)等信息。而method_imp的数据类型是IMP,它是一个函数指针,后面会重点提及。

Ivar

Ivar表示类中的实例变量,在runtime.h文件中找到它的定义:

Ivar其实就是一个指向objc_ivar结构体指针,它包含了变量名(ivar_name)、变量类型(ivar_type)等信息

IMP

在上面讲Method时就说过,IMP本质上就是一个函数指针,指向方法的实现,在objc.h找到它的定义:

当你向某个对象发送一条信息,可以由这个函数指针来指定方法的实现,它最终就会执行那段代码,这样可以绕开消息传递阶段而去执行另一个方法实现。

Cache

顾名思义,Cache主要用来缓存,那它缓存什么呢?我们先在runtime.h文件看看它的定义:

Cache其实就是一个存储Method的链表,主要是为了优化方法调用的性能。当对象receiver调用方法message时,首先根据对象receiver的isa指针查找到它对应的类,然后在类的methodLists中搜索方法,如果没有找到,就使用super_class指针到父类中的methodLists查找,一旦找到就调用方法。如果没有找到,有可能消息转发,也可能忽略它。但这样查找方式效率太低,因为往往一个类大概只有20%的方法经常被调用,占总调用次数的80%。所以使用Cache来缓存经常调用的方法,当调用方法时,优先在Cache查找,如果没有找到,再到methodLists查找。

消息发送

前面从objc_msgSend作为入口,逐步深入分析Runtime的数据结构,了解每个数据结构的作用和它们之间关系后,我们正式转入消息发送这个正题。

objc_msgSend函数

在前面已经提过,当某个对象使用语法[receiver message]来调用某个方法时,其实[receiver message]被编译器转化为:

id objc_msgSend ( id self, SEL op, ... );

首先根据receiver对象的isa指针获取它对应的class;

优先在class的cache查找message方法,如果找不到,再到methodLists查找;

如果没有在class找到,再到super_class查找;

一旦找到message这个方法,就执行它实现的IMP。

self与super

为了让大家更好地理解self和super,借用sunnyxx博客iOS程序员6级考试一道题目:下面的代码分别输出什么?

@implementation Son : Father

- (id)init

{

    self = [super init];

    if (self)

    {

        NSLog(@"%@", NSStringFromClass([self class]));

        NSLog(@"%@", NSStringFromClass([super class]));

    }

    return self;

}

@end

self表示当前这个类的对象,而super是一个编译器标示符,和self指向同一个消息接受者。在本例中,无论是[self class]还是[super class],接受消息者都是Son对象,但super与self不同的是,self调用class方法时,是在子类Son中查找方法,而super调用class方法时,是在父类Father中查找方法。

当调用[self class]方法时,会转化为objc_msgSend函数,这个函数定义如下:

id objc_msgSend(id self, SEL op, ...)

这时会从当前Son类的方法列表中查找,如果没有,就到Father类查找,还是没有,最后在NSObject类查找到。我们可以从NSObject.mm文件中看到- (Class)class的实现:

- (Class)class {

    return object_getClass(self);

}

所以NSLog(@"%@", NSStringFromClass([self class]));会输出Son。

当调用[super class]方法时,会转化为objc_msgSendSuper,这个函数定义如下:

id objc_msgSendSuper(struct objc_super *super, SEL op, ...)

objc_msgSendSuper函数第一个参数super的数据类型是一个指向objc_super的结构体,从message.h文件中查看它的定义:

/// Specifies the superclass of an instance.

struct objc_super {

    /// Specifies an instance of a class.

    __unsafe_unretained id receiver;

    /// Specifies the particular superclass of the instance to message.

#if !defined(__cplusplus)  &&  !__OBJC2__

    /* For compatibility with old objc-runtime.h header */

    __unsafe_unretained Class class;

#else

    __unsafe_unretained Class super_class;

#endif

    /* super_class is the first class to search */

};

#endif

结构体包含两个成员,第一个是receiver,表示某个类的实例。第二个是super_class表示当前类的父类。

这时首先会构造出objc_super结构体,这个结构体第一个成员是self,第二个成员是(id)class_getSuperclass(objc_getClass("Son")),实际上该函数会输出Father。然后在Father类查找class方法,查找不到,最后在NSObject查到。此时,内部使用objc_msgSend(objc_super->receiver, @selector(class))去调用,与[self class]调用相同,所以结果还是Son。

三、使用示例

1、方法继承

@interface CFURL : NSURL

+(instancetype)CFURLWithString:(NSString *)string;

@end

#import "CFURL.h"

@implementation CFURL

+(instancetype)CFURLWithString:(NSString *)string{

    CFURL *url = [super URLWithString:string];

    if (url == nil) {

        NSLog(@"url为空");

    }

    return url;

}

@end

//扩展分类

@interface NSURL (url)

+(instancetype)CF_URLWithStr:(NSString *)URLString;

@end

2、方法交换

Git下载:https://github.com/gaoguangxiao/RuntimeMCDemo

#import "NSURL+url.h"

#import@implementation NSURL (url)

+(void)load{

    //最早的方法,比main还早

    NSLog(@"load");

    //1.拿到两个Method

    //2.进行方法交换

    Method m1 = class_getClassMethod([NSURL class], @selector(URLWithString:));

    Method m2 = class_getClassMethod([NSURL class], @selector(CF_URLWithStr:));

    //利用runtime进行方法的交换

    method_exchangeImplementations(m1, m2);

}

+(instancetype)CF_URLWithStr:(NSString *)URLString{

    //交换了两个方法

    NSURL *url = [NSURL CF_URLWithStr:URLString];//注意这里不能再调用系统的方法

    if (!url) {

        NSLog(@"url为空");

    }

    return url;

}

@end

3、分类扩展属性

//.h文件#import"NSObject.h"

@interfaceNSObject(Property)//

@property在分类中只会生成set、get方法的声明 不会生成实现,也不会生成_成员属性@property(nonatomic,copy)NSStringname;

@end-----------------------------------------------

//.m文件

// 定义关联的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

4、修改私有类属性

//按钮标题的字体颜色

-(void)setTextColor:(UIColor *)textColor

{

    _textColor = textColor;

    unsignedintcount = 0;

    Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);

    for(inti =0;i < count;i ++){

        Ivar ivar = ivars[i];

        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];

 if([ivarName isEqualToString:@"_titleTextColor"]) {

  [self setValue:textColor forKey:@"titleTextColor"];

        }

    }

}

四、参考网址

http://www.cocoachina.com/ios/20160914/17579.html 

上一篇下一篇

猜你喜欢

热点阅读