Ownership Qualifiers
- __strong
默认修饰符,强引用,相当于 retain 。 - __unsafe_unretained
弱引用,引用计数不会变化。 - __weak
iOS 5 之后加入,与 __unsafe_unretained 不同之处是,对象释放后,指针将被置为 nil 。 - __auto_releasing
当函数返回值是 auto-released 时,用其修饰。不能修饰属性。
Toll-Free Bridging
- __bridge
最普通的类型转换,ARC 不会修改引用计数。 - __bridge_retained
- 当 C 指针类型的引用计数加一时。
- 一个 Objective-C 函数返回一个 Core Foundation 对象时,释放时用 CFRelease 。
- __bridge_transfer
- Core Foundation 指针转换成 Objective-C 指针,引用计数减一时。
- 使用 Core Foundation 函数创建对象,并将其内存管理转交 ARC 时。
Common ARC Migration Errors
- Casting an Objective-C pointer type to a C pointer type (and vice versa)
当 Objective-C 与 C 指针之间转换时需要要使用 transfer qualifier 。 - Receiver type doesn’t declare the method with selector ARC 依赖的一类函数,在 ARC 出现前,未定义时也可调用,使用 ARC 后,如果调用未定义的这类函数,将出现编译错误。
- performSelector may cause a leak because its selector is unknown ARC 依赖一类函数,当使用 SEL 调用时, ARC 无法做出正确的判断。
- implicit conversion of an Objective-C pointer to ‘void *’ is disallowed with ARC ARC 禁止 void 指针转换成 id ,反之亦然。
id selfPointerAsId = (__bridge void*)self;
- ARC forbids Objective-C objects in structs or unions ARC 的内存管理需要 ownership qualifiers 明确标记。
- NSAutoreleasePool is unavailable: not available in automatic reference counting mode
Workarounds When Using ARC
- Retain Cycles
避免引用循环,使用 _weak or __unsafe_unretained ownership qualifier - Blocks and ARC
避免 Blocks 产生的引用循环,在 ARC 之前使用 __block 修饰变量。
ARC 中 __block 的含义变成了 retained 而不是 copied,所以改用 __weak or __unsafe_unretained 修饰。