类型编码(Type Encodings)

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


为了协助运行时系统,编译器用字符串为每个方法的返回值和参数类型和方法选择器编码。使用的编码方案在其他情况下也很有用,所以它是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

char

i

An int

s

short

l

long

l is treated as a 32-bit quantity on 64-bit programs.

q

long long

C

An unsigned char

I

An unsigned int

S

An unsigned short

L

An unsigned long

Q

An unsigned long long

f

float

d

double

B

A C++ bool or a C99 _Bool

v

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值