ios 委托属性声明中的“弱”和“分配”有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9428500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between 'weak' and 'assign' in delegate property declaration
提问by Firdous
Whats the difference between this:
这有什么区别:
@property (nonatomic, weak) id <SubClassDelegate> delegate;
and this:
和这个:
@property (nonatomic, assign) id <SubClassDelegate> delegate;
I want to use property for delegates.
我想为代表使用财产。
回答by yuji
The only difference between weak
and assign
is that if the object a weak
property points to is deallocated, then the value of the weak
pointer will be set to nil
, so that you never run the risk of accessing garbage. If you use assign
, that won't happen, so if the object gets deallocated from under you and you try to access it, you will access garbage.
weak
和之间的唯一区别assign
是,如果一个weak
属性指向的对象被释放,那么weak
指针的值将被设置为nil
,这样您就永远不会冒访问垃圾的风险。如果你使用assign
,那不会发生,所以如果对象从你下面被释放并且你试图访问它,你将访问垃圾。
For Objective-C objects, if you're in an environment where you can use weak
, then you should use it.
对于 Objective-C 对象,如果您处于可以使用 的环境中weak
,那么您应该使用它。