Objective-C 编码

Objective-C中所有的类、对象、方法、协议、分类等实质都是通过C中的结构体定义,再由runtime的消息机制赋予了它们灵魂,模拟出了面向对象的特性。
为了良好的性能和资源消耗,在消息传递以及执行时需要将携带的信息尽可能的压缩,因此有一套单字符的编码来映射C中结构体与ObjC中的面向对象类型。

类型编码表

类型编码主要应用在对象属性方法参数、返回值上来标明它们的数据类型

@encode(type-name) 编译程序指令可以获取类型对应的编码字符串

Code Meaning
c A char
i An int
s A short
l A longl 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 & long 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)

方法的编码格式

方法的格式编码是一个字符串,按照顺序分段表示对应的信息:

  • 第一段以开始的所有字符为标志,表示返回值类型
  • 第二段以数字为标志,表示方法参数占用空间总长度
  • 第三段以@为开始标志,跟着的数字表示方法所属的对象的地址偏移;为0表示self
  • 第四段以:为标志,后面的数字表示方法的SEL对象的地址偏移
  • 最后以字符+数字为分组标志分组,每一组表示方法的一个参数类型及地址偏移
1
2
3
NSLog(@"%s", method_getTypeEncoding(class_getInstanceMethod([self class], @selector(viewDidAppear:))));

//- (void)viewWillAppear:(BOOL)animated -> v20@0:8B16
  • v 表示返回值为 void
  • 20 表示方法参数的占用空间总长度
  • @0 表示方法的所属对象,其中 0 表示对象地址偏移量为 0(self)
  • :8 表示方法的 SEL 对象,其中 8 表示SEL地址偏移量为 8
  • B16 表示参数为 Bool 类型,地址在偏移量16处 (16 是加上对象和SEL的地址之后的偏移量);一共长 20, Bool 在16处,说明占用了4个字节

属性的编码格式

属性的编码格式同样是一个字符串,它以逗号 , 分隔每一段的信息:

  • 第一段是以 T 开头的字符串,表示属性值类型;T后面跟着类型编码,表示该属性的数据类型
  • 最后一段是以 V_ 开头的字符串,表示属性名
  • 其余信息在字符串中间表示属性的 @property 关键字信息;可能有多段,也可能没有;包含原子性、内存管理语义等
1
2
3
4
5
@property(nonatomic, assign) NSInteger num;
// NSLog(@"%s", property_getAttributes(class_getProperty([self class], "num"))); --> Tq,N,V_num

@property(nonatomic, strong) NSString *name;
// NSLog(@"%s", property_getAttributes(class_getProperty([self class], "name"))); --> T@"NSString",&,N,V_name

property 关键字编码表

Code Meaning
R The property is read-only (readonly).
C The property is a copy of the value last assigned (copy).
& The property is a reference to the value last assigned (retain).
N The property is non-atomic (nonatomic).
G The property defines a custom getter selector name. The name follows the G (for example, GcustomGetter,).
S The property defines a custom setter selector name. The name follows the S (for example, ScustomSetter:,).
D The property is dynamic (@dynamic).
W The property is a weak reference (__weak).
P The property is eligible for garbage collection.
t Specifies the type using old-style encoding.

属性和实例变量的差别

  • 属性用 @property 关键字声明,而实例变量声明在 { }
  • 实例变量默认只有类内部可以访问
  • 属性就是实例变量加上 settergetter 方法
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2017-2021 HonQi

请我喝杯咖啡吧~