美文网首页
iOS - method 底层详解

iOS - method 底层详解

作者: felix6 | 来源:发表于2018-05-03 14:26 被阅读0次

[toc]

参考

method

Method

typedef struct objc_method *Method;

objc_method

objc_method 和 method_t 是等价的

struct objc_method {
    SEL method_name;
    char *method_types;
    IMP method_imp;
};

method_t

method_t 是对 方法 / 函数 的封装, 是苹果内部使用的, 没有公开的类型

方法 / 函数 的底层结构就是 method_t

struct method_t {
    SEL name; // 函数名
    const char *types; // 编码 (返回值类型、参数类型)
    MethodListIMP imp; // 指向函数的指针 (函数地址)

    struct SortBySELAddress :
        public std::binary_function<const method_t&, const method_t&, bool>
    {
        bool operator() (const method_t& lhs,
                         const method_t& rhs)
        { return lhs.name < rhs.name; }
    };
};

using MethodListIMP = IMP;

IMP

指向函数的指针 (函数地址)

代表函数的具体实现

// Objc.h 中 IMP 的定义: 
/// A pointer to the fu nction of a method implementation.
#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ );
#else
typedef id _Nullable (*IMP)(id _Nonnull, SEL _Nonnull, …); // 相当于给id (*)(id, SEL, ...)) 取别名IMP
#endif

任何继承于 NSObject 的类都能自动获得runtime的支持。在类中有一个isa指针, 指向该类定义的成员组成的结构体, 这个结构体是由编译器编译时为类创建的。这个结构体包含一个指向父类的指针和一个hash表, 即 Dispatch table(分发表), 是一张SEL和IMP的对应关系表。值是函数指针IMP, SEL就是查表时所用的键。

SEL 和 IMP 是映射关系, Method Swizzling 可以改变这个映射关系;

SEL的存在只是为了加快方法的查询速度, 省去了字符串(即方法名)比对的时间, 可以直接用SEL生成的KEY去查找, 就像我们直接根据NSDictionary的Key去读取相应的Value一样。

为什么不直接获得函数指针IMP, 而要从SEL这个编号走一圈再回到函数指针呢?

我们可以让一个SEL指向不同的函数指针IMP, 这样就可以完成一个方法名在不同时候执行不同的函数体。另外可以将SEL作为参数传递给不同的类执行。也就是说我们某些业务我们只知道方法名但需要根据不同的情况让不同类执行的时候,SEL可以帮助我们。

SEL

SEL 代表方法\函数名,一般叫做选择器,底层结构跟 char * 类似

typedef struct objc_selector *SEL;

可以通过 @selector()sel_registerName() 获得

SEL selA = @selector(setString:);
SEL selB = sel_registerName("setString:");

在类加载的时候, 编译器会生成与方法相对应的选择子, 并注册到 Objective-C 的 Runtime 运行系统。

不同类中, 无论参数类型是否相同, 只要方法名相同, 所对应的SEL是相同的

所以在OC中, 同一个类(及类的继承体系)中, 不能存在2个同名的方法, 即使参数类型不同也不行。

相同的方法只能对应一个SEL。这也就导致 Objective-C在处理相同方法名且参数个数相同但类型不同的方法方面的能力很差。

当然, 不同的类可以拥有相同的selector, 这个没有问题。不同类的实例对象执行相同的selector时,会在各自的方法列表中去根据selector去寻找自己对应的IMP。

工程中的所有的SEL组成一个Set集合,Set的特点就是唯一,因此SEL是唯一的。

因此,如果我们想到这个方法集合中查找某个方法时,只需要去找到这个方法对应的SEL就行了,SEL实际上就是根据方法名hash化了的一个字符串,而对于字符串的比较仅仅需要比较他们的地址就可以了,可以说速度上无语伦比!!但是,有一个问题,就是数量增多会增大hash冲突而导致的性能下降(或是没有冲突,因为也可能用的是perfect hash)。但是不管使用什么样的方法加速,如果能够将总量减少(多个方法可能对应同一个SEL),那将是最犀利的方法。那么,我们就不难理解,为什么 SEL仅仅是函数名了。

_cmd

OC的编译器在编译后会在每个方法中加2个隐藏的参数:

_cmd : SEL类型的指针, 代表当前方法的 selector。

self : id类型的指针, 指向当前对象的指针。我们平时之所以能在OC函数中调用self, 正是因为函数中有隐藏起来了的self参数

types

types 包含了函数返回值类型、参数类型编码的字符串

/*
"v16@0:8"
v 返回值 void
@ 参数 (id)self
: 参数 (SEL)_cmd
*/
- (void)test;


/*
"i24@0:8i16f20"
i  返回值 int
24 所有参数所占字节数
@  参数1 (id)self
0  参数1 从第0个字节开始
:  参数2 (SEL)_cmd
8  参数2 从第8个字节开始
i  参数3 int
16 参数3 从第16个字节开始
f  参数4 float
20 参数4 从第20个字节开始
*/
- (int)test:(int)age height:(float)height; 
@encode

@encode是编译器指令之一。

@encode返回一个给定的Objective-C 类型编码(Objective-C Type Encodings)。

这是一种内部表示的字符串,类似于 ANSI C 的 typeof 操作。

苹果的 Objective-C 运行时库(runtime)内部利用类型编码帮助加快消息分发。

NSLog(@"%s", @encode(id)); // @
NSLog(@"%s", @encode(SEL)); // :
type encodings

官方文档

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)

APIs

/// NSObject.h
// If the receiver is an instance, aSelector should refer to an instance method; 
// if the receiver is a class, it should refer to a class method.
- (IMP)methodForSelector:(SEL)aSelector;

// 向类请求实例方法的IMP。
+ (IMP)instanceMethodForSelector:(SEL)aSelector;
Method _Nullable class_getInstanceMethod(Class _Nullable cls, SEL _Nonnull name);



// 向runtime系统注册一个方法名称, 并生成SEL和方法名称的映射, 最后返回SEL。如果该方法名称已经注册, 则直接返回其对应的SEL。
SEL sel_registerName(const char *str); 

SEL methodId = @selector(methodName); // OC编译器的命令

SEL method_getName(Method m);

SEL NSSelectorFromString(NSString *aSelectorName); // NSObjCRuntime.h

NSString *NSStringFromSelector(SEL aSelector); // NSObjCRuntime.h

const char *sel_getName(SEL aSelector); // runtime.h



IMP _Nullable class_getMethodImplementation(Class _Nullable cls, SEL _Nonnull name);

IMP _Nonnull method_getImplementation(Method _Nonnull m);

IMP _Nonnull imp_implementationWithBlock(id _Nonnull block)
    
IMP _Nonnull method_setImplementation(Method _Nonnull m, IMP _Nonnull imp);

IMP _Nullable class_replaceMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, const char * _Nullable types);


BOOL class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, const char * _Nullable types);

示例

// 获取当前方法的IMP, 可使用隐藏参数self和_cmd。
IMP currentIMP = [[self class] instanceMethodForSelector:_cmd];

相关文章

  • iOS - method 底层详解

    [toc] 参考 method Method objc_method objc_method 和 method_t...

  • iOS底层探索 --- Runtime(二)Method Swi

    本文摘抄自iOS 开发:『Runtime』详解(二)Method Swizzling[https://www.ji...

  • iOS面试相关

    GCD 系列知识总结 NSOperation相关知识总结 iOS Runtime详解 黑魔法 Method_Swi...

  • 底层原理

    iOS底层原理总结 - Category的本质 KVO详解及底层实现青少年一定要读的KVO指南 iOS 底层解析w...

  • iOS 底层 day12 runtime method详解

    一、class_rw_t 数据结构 二、method_t 数据结构 和其他编程语言一样,一个方法我们需要保存它的函...

  • Runloop

    Runloop 实现原理及应用iOS - RunLoop 底层源码详解及具体运用

  • iOS 底层 method_t 中的 types

    iOS 底层 method_t 中的 types 上篇我们说到,method_t 其实就是一个结构体,存储着方法的...

  • method

    method 详解

  • iOS - KVO

    [toc] 参考 KVO KVC 【 iOS--KVO的实现原理与具体应用 】 【 IOS-详解KVO底层实现 】...

  • OC底层原理15-Method Swizzling

    iOS--OC底层原理文章汇总[/p/14911da92f74] Method Swizzling 方法交换,这是...

网友评论

      本文标题:iOS - method 底层详解

      本文链接:https://www.haomeiwen.com/subject/nogkrftx.html