objective-c中关于类型编码的解释

时间:2023-12-30 19:33:14

在某些情况下,我们需要动态的向一个类插入一个实例方法(也可以是一个类方法);这时我们可以用class_addMethod函数来完成:

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

在Objective-C Runtime Reference 中可以看到各个参数的含义:

Parameters
**cls**
The class to which to add a method.

**name**
A selector that specifies the name of the method being added.

**imp**
A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.

**types**
An array of characters that describe the types of the arguments to the method. For possible values, see Objective-C Runtime Programming Guide > Type Encodings. Since the function must take at least two arguments—self and _cmd, the second and third characters must be “@:” (the first character is the return type).

前面几个参数比较好理解,我们来看看最后一个:这是一个字符串按照imp的签名依次排列返回值和各个参数。apple开发者官网有对应的编码:

Type Encodings

我们也可以用@encode来查看实际的编码,比如:

NSLog(@"%s",@encode(int *));