Objective-C 类型编码

原文地址:https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html

为了辅助运行时系统,编译器将对每个方法的返回和参数类型进行编码,并将字符串与方法选择器相关联。使用的编码方案在其他上下文中也很有用,因此公开了 @encode() 编译器指令。当给定类型时,@encode() 返回对该类型编码的字符串。该类型可以是基本类型,例如 int、指针、标记结构体或联合(union),或类名——任何类型,实际上可以用作 C sizeof() 运算符的参数。

char *buf1 = @encode(int **);
char *buf2 = @encode(struct key);
char *buf3 = @encode(Rectangle);

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) 和 double 一样返回 d

数组类型编码由方括号括起来,数组中的元素个数紧跟在左括号后指定,在数组类型之前。比如,12 个指向浮点数的指针将这样编码:

[12^f]

结构体和共用体的编码:

typedef struct example {
    id   anObject;
    char *aString;
    int  anInt;
} Example

// 编码如下:
{example=@*i}

对象和结构体一样,例如,传递 NSObject 类名给 @encode() 将产生以下编码:

{NSObject=#}

Objective-C 方法编码

对于协议方法的类型修饰符,虽然 @encode() 不直接返回它们,但运行时系统使用下列额外的编码。

Code Meaning
r const
n in
N inout
o out
O bycopy
R byref
V oneway

  • Apple: Objective-C Runtime Programming Guide

你可能感兴趣的:(Objective-C 类型编码)