YOU'VE MADE A BRAVE DECISION, WELCOME.

每一个不曾起舞的日子都是对生命的辜负。

初识Runtime

其实看了一些别人讲的教程,对Runtime的认识还是很模糊,希望之后多实践可以加深了解


  • 定义

    • 实现Objective-C语言的C库
    • 对象可以是C语言中的结构体表示
    • 方法可以用C函数实现
  • 最终执行代码

    • 如果执行[object doSomething];时
    • 首先会向消息接受者objec发送一条消息doSomething;
    • Runtime会根据消息接收者是否能响应做出不同的反应
  • Runtime中的消息

    • message(消息)
      • 一种抽象,包括了函数名+参数列表
    • method(方法)
    • selector(方法选择器)
      • 通过SEL定义,描述message或者method,可以通过selector来检索方法
  • _cmd关键字

    • 通过这个关键字可以取到当前对应的SEL
  • OC下代码:[tableview cellForRowAtIndexPath:indexPath]在编译时Runtime会转换成【发送消息】objc_msgSend(tableview, @selector(cellForRowAtIndexPath:), indexPath);

  • 常见方法

    • unsigned int count;

    • 获取属性列表

      • objc_property_t *propertyList = class_copyPropertyList([self class], &count);
    • 获取方法列表

      • Method *methodList = class_copyMethodList([self class], &count);
    • 获取成员变量列表

      • Ivar *ivarList = class_copyIvarLis([self class], &count);
    • 获取协议列表

      • __unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count);
    • 有一个Person类,和创建的xiaoming对象,有test1、test2两种方法

    • 获取类方法

      • 1
        2
        3
        4
        5
        Class PersonClass = object_getClass([Person class]);
        SEL sel = @selector(test1);
        Method method = class_getInstanceMethod(xiaomingClass, sel);
    • 获取实例方法

      • 1
        2
        3
        4
        5
        Class PersonClass = object_getClass([xiaoming class]);
        SEL sel = @selector(test2);
        Method method = class_getInstanceMethod(xiaomingClass,sel);
    • 增添方法

      • class_addMethod(xiaomingClass, sel, method_getImplementation(method), method_getTypeEncoding(method));
    • 替换原方法

      • class_replaceMethod(toolClass, sel, method_getImplementation(method), method_getTypeEncoding(method));
    • 交换两个方法

      • method_exchangeImplementation(method1,method2);
  • 功能作用

    • 动态的添加成员变量和方法
    • 动态交换两个方法的实现
    • 拦截并替换两个方法
    • 在方法上增添额外的功能
    • 实现NSCoding的归档和解档
    • 实现字典模型的自动转换
  • 参数概念

    • objc_msgSend
      • 发送基本消息
      • objc_msgSend_stret发送返回值为结构体的消息
      • objc_msgSend_fpret发送返回值为浮点类型的消息
      • 还是使用objc_msgSend_fp2ret发送返回值为浮点类型的消息
    • SEL
      • 是selector在Objc的表示,selector是方法选择器
      • 不同类中相同名字的方法对应的方法选择器是相同的
    • id
      • 一个指向实例的指针
      • objc_object包含一个isa指针,可以通过它找到实例所属的类,但不能依靠它找到实例的类型,而是用class来确定类型
  • objc_msgSend函数

    • 通过对象的isa指针找到它的类class
    • 在class的method list里找到该消息的实现
    • 如果没有找到,则到super_class(父类)中寻找
    • 一旦找到消息的实现,就去执行他的IMP
  • IMP

    • 函数指针
  • 关联对象

    • 对象在内存可以当做是一个结构体对象,不能动态的变化,即无法在运行时给对象增添成员变量
    • 通过兑关联对象的方法变相的给对象增加一个成员变量