程序员每天写1000字iOS Developer

ios runtime 详解

2018-02-10  本文已影响265人  SunnyLeong

前言

在开始之前建议先阅读iOS runtime的基础理解篇:iOS内功篇:runtime

有筒子在面试的时候,遇到这样一个问题:“你知道成员变量的本质是什么吗?”,筒子立马懵逼了,成员变量的本质?成员变量就是成员变量啊,平时只管用,还有什么更深层的含义?本文着重介绍runtime中成员变量和属性的定义和使用。

名词解析

成员变量

1、定义:
Ivar: 实例变量类型,是一个指向objc_ivar结构体的指针

typedef struct objc_ivar *Ivar;

2、操作函数:

// 获取所有成员变量
class_copyIvarList

// 获取成员变量名
ivar_getName

// 获取成员变量类型编码
ivar_getTypeEncoding

// 获取指定名称的成员变量
class_getInstanceVariable

// 获取某个对象成员变量的值
object_getIvar

// 设置某个对象成员变量的值
object_setIvar

3、使用实例:
Model的头文件声明如下:

    @interface Model : NSObject {
        NSString * _str1;
    }
    @property NSString * str2;
    @property (nonatomic, copy) NSDictionary * dict1;
    @end

获取其成员变量:

    unsigned int outCount = 0;
    Ivar * ivars = class_copyIvarList([Model class], &outCount);
    for (unsigned int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        const char * name = ivar_getName(ivar);
        const char * type = ivar_getTypeEncoding(ivar);
        NSLog(@"类型为 %s 的 %s ",type, name);
    }
    free(ivars);

打印结果:

runtimeIvar[602:16885] 类型为 @"NSString" 的 _str1 
runtimeIvar[602:16885] 类型为 @"NSString" 的 _str2 
runtimeIvar[602:16885] 类型为 @"NSDictionary" 的 _dict1 

属性

1、定义:
objc_property_t:声明的属性的类型,是一个指向objc_property结构体的指针

typedef struct objc_property *objc_property_t;

2、操作函数:

// 获取所有属性
class_copyPropertyList

说明:使用class_copyPropertyList并不会获取无@property声明的成员变量

// 获取属性名
property_getName

// 获取属性特性描述字符串
property_getAttributes

// 获取所有属性特性
property_copyAttributeList

说明:
property_getAttributes函数返回objc_property_attribute_t结构体列表,objc_property_attribute_t结构体包含name和value,常用的属性如下:

属性类型  name值:T  value:变化
编码类型  name值:C(copy) &(strong) W(weak) 空(assign) 等 value:无
非/原子性 name值:空(atomic) N(Nonatomic)  value:无
变量名称  name值:V  value:变化

使用property_getAttributes获得的描述是property_copyAttributeList能获取到的所有的name和value的总体描述,如 T@"NSDictionary",C,N,V_dict1

3、使用实例:

    unsigned int outCount = 0;
    objc_property_t * properties = class_copyPropertyList([Model class], &outCount);
    for (unsigned int i = 0; i < outCount; i ++) {
        objc_property_t property = properties[i];
        //属性名
        const char * name = property_getName(property);
        //属性描述
        const char * propertyAttr = property_getAttributes(property);
        NSLog(@"属性描述为 %s 的 %s ", propertyAttr, name);

        //属性的特性
        unsigned int attrCount = 0;
        objc_property_attribute_t * attrs = property_copyAttributeList(property, &attrCount);
        for (unsigned int j = 0; j < attrCount; j ++) {
            objc_property_attribute_t attr = attrs[j];
            const char * name = attr.name;
            const char * value = attr.value;
            NSLog(@"属性的描述:%s 值:%s", name, value);
        }
        free(attrs);
        NSLog(@"\n");
    }
    free(properties);

打印结果:

runtimeIvar[661:27041] 属性描述为 T@"NSString",&,V_str2 的 str2 
runtimeIvar[661:27041] 属性的描述:T 值:@"NSString"
runtimeIvar[661:27041] 属性的描述:& 值:
runtimeIvar[661:27041] 属性的描述:V 值:_str2
runtimeIvar[661:27041] 
runtimeIvar[661:27041] 属性描述为 T@"NSDictionary",C,N,V_dict1 的 dict1 
runtimeIvar[661:27041] 属性的描述:T 值:@"NSDictionary"
runtimeIvar[661:27041] 属性的描述:C 值:
runtimeIvar[661:27041] 属性的描述:N 值:
runtimeIvar[661:27041] 属性的描述:V 值:_dict1
runtimeIvar[661:27041] 

应用实例

1、Json到Model的转化

在开发中相信最常用的就是接口数据需要转化成Model了(当然如果你是直接从Dict取值的话。。。),很多开发者也都使用著名的第三方库如JsonModel、Mantle或MJExtension等,如果只用而不知其所以然,那真和“搬砖”没啥区别了,下面我们使用runtime去解析json来给Model赋值。

原理描述:用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。
核心方法:在NSObject的分类中添加方法:

- (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;

}

读者可以进一步思考:
1、如何识别基本数据类型的属性并处理
2、空(nil,null)值的处理
3、json中嵌套json(Dict或Array)的处理
尝试解决以上问题,你也能写出属于自己的功能完备的Json转Model库。

2、快速归档

有时候我们要对一些信息进行归档,如用户信息类UserInfo,这将需要重写initWithCoder和encodeWithCoder方法,并对每个属性进行encode和decode操作。那么问题来了:当属性只有几个的时候可以轻松写完,如果有几十个属性呢?那不得写到天荒地老?。。。

原理描述:用runtime提供的函数遍历Model自身所有属性,并对属性进行encode和decode操作。
核心方法:在Model的基类中重写方法:

- (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];
    }
}

3、访问私有变量

我们知道,OC中没有真正意义上的私有变量和方法,要让成员变量私有,要放在m文件中声明,不对外暴露。如果我们知道这个成员变量的名称,可以通过runtime获取成员变量,再通过getIvar来获取它的值。
方法:

    Ivar ivar = class_getInstanceVariable([Model class], "_str1");
    NSString * str1 = object_getIvar(model, ivar);

欢迎大家交流探讨。

作者:明仔Su











1.背景知识

哪里涉及到runtime

1.1 OC的方法调用流程

下面以实例对象调用方法[blackDog walk]为例描述方法调用的流程:

1、编译器会把`[blackDog walk]`转化为`objc_msgSend(blackDog,SEL)`,SEL为@selector(walk)。

2、Runtime会在blackDog对象所对应的Dog类的方法缓存列表里查找方法的SEL

3、如果没有找到,则在Dog类的方法分发表查找方法的SEL。(类由对象isa指针指向,方法分发表即methodList)

4、如果没有找到,则在其父类(设Dog类的父类为Animal类)的方法分发表里查找方法的SEL(父类由类的superClass指向)

5、如果没有找到,则沿继承体系继续下去,最终到达NSObject类。

6、如果在234的其中一步中找到,则定位了方法实现的入口,执行具体实现

7、如果最后还是没有找到,会面临两种情况:``(1) 如果是使用`[blackDog walk]`的方式调用方法````(2) 使用`[blackDog performSelector:@selector(walk)]`的方式调用方法`

1.2 消息转发流程

1、动态方法解析
接收到未知消息时(假设blackDog的walk方法尚未实现),runtime会调用+resolveInstanceMethod:(实例方法)或者+resolveClassMethod:(类方法)

2、备用接收者
如果以上方法没有做处理,runtime会调用- (id)forwardingTargetForSelector:(SEL)aSelector方法。
如果该方法返回了一个非nil(也不能是self)的对象,而且该对象实现了这个方法,那么这个对象就成了消息的接收者,消息就被分发到该对象。
适用情况:通常在对象内部使用,让内部的另外一个对象处理消息,在外面看起来就像是该对象处理了消息。
比如:blackDog让女朋友whiteDog来接收这个消息

3、完整消息转发
在- (void)forwardInvocation:(NSInvocation *)anInvocation方法中选择转发消息的对象,其中anInvocation对象封装了未知消息的所有细节,并保留调用结果发送到原始调用者。
比如:blackDog将消息完整转发給主人dogOwner来处理

2.成员变量和属性

''你知道成员变量的本质是什么吗?"
答案在这里:OS runtime实战应用:成员变量和属性

2.1 json->model

原理描述:用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。
核心方法:在NSObject的分类中添加方法

- (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;

}

2.2 一键序列化

原理描述:用runtime提供的函数遍历Model自身所有属性,并对属性进行encode和decode操作。
核心方法:在Model的基类中重写方法:

- (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];
    }
}

2.3 访问私有变量

我们知道,OC中没有真正意义上的私有变量和方法,要让成员变量私有,要放在m文件中声明,不对外暴露。如果我们知道这个成员变量的名称,可以通过runtime获取成员变量,再通过getIvar来获取它的值。方法:

Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);

3. 关联对象

如何給NSArray添加一个属性(不能使用继承)
答案在这里:iOS runtime实战应用:关联对象
polen:
OC的分类允许给分类添加属性,但不会自动生成getter、setter方法
所以常规的仅仅添加之后,调用的话会crash

runtime如何关联对象

//关联对象
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
//获取关联的对象
id objc_getAssociatedObject(id object, const void *key)
//移除关联的对象
void objc_removeAssociatedObjects(id object)

应用,如何关联:

- (void)setCustomTabbar:(UIView *)customTabbar {
    //这里使用方法的指针地址作为唯一的key
    objc_setAssociatedObject(self, @selector(customTabbar), customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)customTabbar {
    return objc_getAssociatedObject(self, @selector(customTabbar));
}

4.Method Swizzling

method Swizzling原理
每个类都维护一个方法(Method)列表,Method则包含SEL和其对应IMP的信息,方法交换做的事情就是把SEL和IMP的对应关系断开,并和新的IMP生成对应关系

+ (void)load {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        Class selfClass = object_getClass([self class]);

        SEL oriSEL = @selector(imageNamed:);
        Method oriMethod = class_getInstanceMethod(selfClass, oriSEL);

        SEL cusSEL = @selector(myImageNamed:);
        Method cusMethod = class_getInstanceMethod(selfClass, cusSEL);

        BOOL addSucc = class_addMethod(selfClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
        if (addSucc) {
            class_replaceMethod(selfClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
        }else {
            method_exchangeImplementations(oriMethod, cusMethod);
        }

    });
}

自己使用过例子:
使用场景,在iOS7中如果viewdidappear还没有完成,就立刻执行push或者pop操作会crash,见我之前写过的一篇文章iOS7中的pop导致的crash

解决方案就是利用method swizzing, 将系统的viewdidappear替换为自己重写的sofaViewDidAppear

@implementation UIViewController (APSafeTransition)

+ (void)load
{
    Method m1;
    Method m2;

    m1 = class_getInstanceMethod(self, @selector(sofaViewDidAppear:));
    m2 = class_getInstanceMethod(self, @selector(viewDidAppear:));
    method_exchangeImplementations(m1, m2);
}

runtime这种消息机制,并非iOS特有,其他系统下也有类似的东西,比如windows下的MFC等等. 这里是cocoachina下所有和runtime相关的文章,请点击查看

作者:pingpong_龘

参考1
参考2


RunTime基础

基础路径图:


1

在学习RunTime的基础时, 我们要搞清楚一些重要的东西, 一些专业术语:

我们可以从这些东西里获取到指定类的所有信息, 无论是公开的, 还是私有的, 全部都可以拿到, 并且操作.

PS: 但操作私有方法的时候, 注意不要用来上架, 除非你有方法让苹果审核的时候通过.


RunTime进阶

进阶路径图:

<figure> 2

<figcaption></figcaption>

</figure>

在学习RunTime进阶的时候, 我们就要了解更加的深入.

消息机制:

对象关联:

对象关联的策略:

动态方法解析:


RunTime应用

应用路径图:

3

在学习完RunTime之后, 我们就可以应用到我们的实际开发中.

Category

Class

Model


RunTime实例开发场景

在实际开发中, 我们有一些实例场景会用到RunTime:

Runtime Method Swizzling开发实例汇总


RunTime面试题及答案

问题: objc在向一个对象发送消息时, 发生了什么?
1.根据对象的isa指针找到类对象id, 在查询类对象里面的methodLists方法函数列表
2.如果没有在好到, 在沿着superClass, 寻找父类,再在父类methodLists方法列表里面查询
3.最终找到SEL, 根据idSEL确认IMP(指针函数), 在发送消息.
问题: 什么时候会报unrecognized selector错误? iOS有哪些机制来避免走到这一步?
1.当发送消息的时候, 我们会根据类里面的methodLists列表去查询我们要动用的SEL, 当查询不到的时候, 我们会一直沿着父类查询
2.当最终查询不到的时候我们会报unrecognized selector错误, 当系统查询不到方法的时候, 会调用+(BOOL)resolveInstanceMethod:(SEL)sel动态解释的方法来给我一次机会来添加, 调用不到的方法.
3.或者我们可以再次使用-(id)forwardingTargetForSelector:(SEL)aSelector重定向的方法来告诉系统,该调用什么方法,一来保证不会崩溃.
问题: 能否向编译后得到的类中增加实例变量?能否向运行时创建的类中添加实例变量? 为什么?
1.不能向编译后得到的类增加实例变量.
2.能向运行时创建的类中添加实例变量.
解释:
1. 编译后的类已经注册在runtime中,类结构体中的objc_ivar_list实例变量的链表和instance_size实例变量的内存大小已经确定,runtime会调用class_setvarlayoutclass_setWeaklvarLayout来处理strong``weak引用.所以不能向存在的类中添加实例变量.
2. 运行时创建的类是可以添加实例变量,调用class_addIvar函数. 但是的在调用objc_allocateClassPair之后,objc_registerClassPair之前,原因同上.
问题: runtime如何实现weak变量的自动置nil?
1.runtime对注册的类, 会进行布局,对于weak对象会放入一个hash表中。 用weak指向的对象内存地址作为key,当此对象的引用计数为0的时候会dealloc.
2.假如weak指向的对象内存地址是A,那么就会以A为键, 在这个weak表中搜索,找到所有以A为键的weak对象,从而设置为nil.
问题: 给类添加一个属性后,在类结构体里哪些元素会发生变化
1.instance_size :实例的内存大小.
2.objc_ivar_list *ivars : 属性列表.

总结

好了, 终于到尾声了, 希望大家可以在我的文章里学到知识, 早日迎娶白富美, 走上人生巅峰.

作者:CainLuo

上一篇 下一篇

猜你喜欢

热点阅读