iOS Sharing #02 | 2019-03-30

目录

一、类方法去哪里找?

二、isa指针有几种类型么?

三、分类的方法具体是在何时添加到类的方法列表中?

四、class_addMethod()都须要什么参数?

五、iOS消息转发流程


一、类方法去哪里找?

答: 见上一期《iOS Sharing #01 | 2019-03-23》第5问

五、实例方法去哪里找?git


二、isa指针有几种类型么?

答: isa指针分,指针类型和非指针类型,32位只作地址保存,非嵌入式64位架构下,包含除类地址外的其余信息。

isa指针类型


三、分类的方法具体是在何时添加到类的方法列表中?

答: 类在编译后会以 class_ro_t 的结构把类的信息存储在 bits 里,运行时的 realizeClass 以后,会把 ro 中的全部信息拷贝到 bits 的 data 内,即以 class_rw_t 的形式存在,分类里的方法即在这个时候添加到类的方法表里,并在方法表数组的最前面

四、class_addMethod()都须要什么参数?

答:
/** * Adds a new method to a class with a given name and implementation. * * @param cls The class to which to add a method. * @param name A selector that specifies the name of the method being added. * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd. * @param types An array of characters that describe the types of the arguments to the method. * * @return YES if the method was added successfully, otherwise NO * (for example, the class already contains a method implementation with that name). * * @note class_addMethod will add an override of a superclass's implementation, * but will not replace an existing implementation in this class. * To change an existing implementation, use method_setImplementation. */
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp,
const char *types)
__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

复制代码
  • 给类添加一个新的方法和该方法的具体实现
  • BOOL: 返回值,YES -------方法添加成功 NO --------方法添加失败
  • Class cls: 将要给添加方法的类,传的类型 [类名 class]
  • SEL name: 将要添加的方法名,传的类型 @selector(方法名)
  • IMP imp:实现这个方法的函数 ,传的类型
    • 一、C语言写法:(IMP)方法名
    • 二、OC的写法:class_getMethodImplementation(self,@selector(方法名:))
  • const char *types:表示咱们要添加的方法的返回值和参数
  • "v@:@":
    • 'v'是添加方法无返回值
    • '@'表示是id(也就是要添加的类)
    • ':'表示添加的方法类型
    • '@'表示参数类型

const char *types含义表:
github

Code Meaning
c A char
i An int
s A short
l A long l is treated as a 32-bit quantity on 64-bit programs.
q A long long
C An unsigned char
I An unsigned int
S An unsigned short
L An unsigned long
Q An unsigned long long
f A float
d A double
B A C++ bool or a C99 _Bool
v A void
* A character string (char *)
@ An object (whether statically typed or typed id)
# A class object (Class)
: A method selector (SEL)
[array type] An array
{name=type...} A structure
(name=type...) A union
bnum A bit field of num bits
^type A pointer to type
? An unknown type (among other things, this code is used for function pointers)

注意:
用这个方法添加的方法是没法直接调用的,必须用performSelector:调用。 由于performSelector是运行时系统负责去找方法的,在编译时候不作任何校验;若是直接调用编译是会自动校验。 添加方法是在运行时添加的,你在编译的时候尚未这个本类方法,因此固然不行。数组


五、iOS消息转发流程

答:
消息转发机制基本分为三个步骤:
  • 一、动态方法解析
  • 二、备用接受者
  • 三、完整转发

代码架构

流程

类方法: app

类方法

实例方法: ide

实例方法

详细流程: 函数

详细流程

感谢大佬提供的图片。ui


仓库

本篇相关代码this


联系方式

邮箱: adrenine@163.com
spa

邮箱: holaux@gmail.com

邮箱: ledahapple@icloud.com

相关文章
相关标签/搜索