2. Objective-c语言中的ARC(AutomaticReference Counting)
在ARC中与内存管理有关的标识符,可以分为变量标识符和属性标识符,对于变量默认为__strong,而对于属性默认为unsafe_unretained。也存在autoreleasepool。
对于变量的标识符有:
(1) __strong,is the default. An object remains “alive” as long as there is a strong pointerto it.
(2) __weak,specifies a reference that does not keep the referenced object alive. A weakreference is set to nil when there are no strong references to the object.
(3)__unsafe_unretained,specifies a reference that does not keep the referenced object alive and is notset to nil when there are no strong references to the object. If the object itreferences is deallocated, the pointer is left dangling.
(4)__autoreleasing,is used to denote arguments that are passed by reference (id *) and areautoreleased on return,managedby Autoreleasepool.
对于变量标识符的用法:
__strong Number* num = [[Number alloc]init];
在ARC内存管理模式下,其属性的标识符存在以下几种:
@property (nonatomic/atomic, assign/retain/strong/weak/unsafe_unretained/copy,readonly/readwrite) Number* num;//默认为unsafe_unretained
其中assign/retain/copy与MRC下property的标识符意义相同,strong类似与retain,assign类似于unsafe_unretained,strong/weak/unsafe_unretained与ARC下变量标识符意义相同,只是一个用于属性的标识,一个用于变量的标识(带两个下划短线__)。所列出的其他的标识符与MRC下意义相同。
(1)对于assign,你可以对标量类型(如int)使用这个属性。你可以想象一个float,它不是一个对象,所以它不能retain、copy。
(2)对于copy,指定应该使用对象的副本(深度复制),前一个值发送一条release消息。基本上像retain,但是没有增加引用计数,是分配一块新的内存来放置它。特别适用于NSString,如果你不想改变现有的,就用这个,因为NSMutableString,也是NSString。
对于Core Foundation与objective-cObject进行交换时,需要用到的ARC管理机制有:
(1) (__bridge_transfer<NSType>) op oralternatively CFBridgingRelease(op) iSUSEd to consume a retain-count of a CFTypeRef whiletransferring it over to ARC. This could also be represented by id someObj =(__bridge <NSType>) op; CFRelease(op);
(2) (__bridge_retained<CFType>) op oralternatively CFBridgingRetain(op) isused to hand an NSObject overto CF-land while giving it a +1 retain count. You should handle a CFTypeRefyoucreate this way the same as you would handle a result of CFStringCreateCopy().This could also be represented by CFRetain((__bridge CFType)op); CFTypeRef someTypeRef =(__bridge CFType)op;
(3) __bridge justcasts between pointer-land and Objective-C object-land. If you have noinclination to use the conversions above, use this one.
