为了协助运行时系统,编译器用字符串为每个方法的返回值和参数类型和方法选择器编码。使用的编码方案在其他情况下也很有用,所以它是public 的,可用于@encode() 编译器指令。当给定一个类型参数,返回一个编码类型字符串。类型可以是一个基本类型如int,指针,结构或联合标记,或任何类型的类名,事实上,都可以作为C sizeof() 运算符的参数。
char *buf1 = @encode(int **);
char *buf2 = @encode(struct key);
char *buf3 = @encode(Rectangle);下表列出了类型代码。注意,当编码一个对象用于归档或分配时,有许多代码时重叠的。然而,在编写编码器时,这里有些代码不能使用。也有些代码可以使用,但不是@encode()所产生的。(关于编码对象的归档和分配的更多信息,可见基础框架引用中NSCode类规范。)
|
表6-1 Objective-C类型编码 | |
|
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) |
重要:Objective-C 不支持long double 类型。@encode(long double) 返回d,和double编码一样。
数组类型代码是包含在方括号中,在开括号后,数组类型前指定数组中元素的个数。例如,包含12个指向float类型的指针将编码为:
[12^f]结构在括号中指定,在圆括号中结合。最先列出结构标记,然后是等号和序列中列出的结构的范围代码
typedef struct example {
id anObject;
char *aString;
int anInt;
} Example;结构编码如下:
{example=@*i}相同的编码决定定义的类型名称(Example)或者结构标记(example) 是否传递给@encode()。结构指针的编码携带相同数量结构字段信息:
^{example=@*i}然而,另一个间接层删除内部类型规范:
^^{example}对象被当做结构。例如,传递NSObject类名到@encode() 产生如下编码:
{NSObject=#}NSObject类声明一个实例变量,isa,作为类型类。
注意:尽管@encode()指令不返回它们,在协议中用来声明方法时,运行时系统使用表6-2中列出的额外编码列表来限定类型。
|
表6-2 Objective-C方法编码 | |
|
Code |
Meaning |
|
r |
const |
|
n |
in |
|
N |
inout |
|
o |
out |
|
O |
bycopy |
|
R |
byref |
|
V |
oneway |
官方地址:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100-SW1

本文深入探讨了Objective-C中用于方法返回类型、参数类型和方法选择器编码的机制,包括基本类型、指针、结构、联合、类名的编码方式,以及如何使用@encode()指令进行类型编码。
4232

被折叠的 条评论
为什么被折叠?



