IOS strong 和 weak

来源:互联网 发布:c语言二叉树的层次遍历 编辑:程序博客网 时间:2024/04/30 04:34

iOS 5 中对属性的设置新增了strong 和weak关键字来修饰属性(iOS  5 之前不支持ARC)

strong 用来修饰强引用的属性;

@property (strong) SomeClass * aObject; 
对应原来的 
@property (retain) SomeClass * aObject; 和 @property (copy) SomeClass * aObject; 

weak 用来修饰弱引用的属性;
@property (weak) SomeClass * aObject; 
对应原来的 
@property (assign) SomeClass * aObject; 

__weak, __strong 用来修饰变量,此外还有 __unsafe_unretained, __autoreleasing 都是用来修饰变量的。
__strong 是缺省的关键词。
__weak 声明了一个可以自动 nil 化的弱引用。
__unsafe_unretained 声明一个弱应用,但是不会自动nil化,也就是说,如果所指向的内存区域被释放了,这个指针就是一个野指针了。

__autoreleasing 用来修饰一个函数的参数,这个参数会在函数返回的时候被自动释放。


(weak和strong)不同的是: weak,当一个对象不再有strong类型的指针指向它的时候它会被释放  ,即使还有weak型指针指向它。

一旦最后一个strong型指针离去 ,这个对象将被释放,所有剩余的weak型指针都将被清除。

//

ou either have ARC on or off for a  particular file. If its on you cannot use retain release autorelease  etc... Instead you use strong weak for properties or __strong __weak for  variables (defaults to __strong). Strong is the equivalent to retain,  however ARC will manage the release for you.  

The  only time you would want to use weak, is if you wanted to avoid retain  cycles (e.g. the parent retains the child and the child retains the  parent so neither is ever released).

The  'toll free bridging' part (casting from NS to CF) is a massive headache  by the looks of things. You still have to manually manage CFRelease()  and CFRetain() for CF objects. When you convert them back to NS objects  you have to tell the compiler about the retain count so it know what you  have done.

Weak references are not supported in Mac OS X v10.6 and iOS 4. 


大 概就是说 weak 和 strong 属性只有在你打开ARC时才会被要求使用,这时你是不能使用retain release  autorelease 操作的,因为ARC会自动为你做好这些操作,但是你需要在对象属性上使用weak  和strong,其中strong就相当于retain属性,而weak相当于assign。

只有一种情况你需要使用weak(默认是strong),就是为了避免retain cycles(就是父类中含有子类{父类retain了子类},子类中又调用了父类{子类又retain了父类},这样都无法release)

若引用在mac os x v10.6和ios4中不支持