问题描述
ARC 引入的属性有两个新的内存管理属性,strong
和 weak
.
There are two new memory management attributes for properties introduced by ARC, strong
and weak
.
除了copy
,这显然是完全不同的东西,strong
vs retain
和 有什么区别吗?弱
vs assign
?
Apart from copy
, which is obviously something completely different, are there any differences between strong
vs retain
and weak
vs assign
?
根据我的理解,这里唯一的区别是 weak
会将 nil
分配给指针,而 assign
不会,这意味着一旦指针被释放,当我向指针发送消息时,程序就会崩溃.但是如果我使用 weak
,这将永远不会发生,因为发送到 nil
的消息不会做任何事情.
From my understanding, the only difference here is that weak
will assign nil
to the pointer, while assign
won't, which means the program will crash when I send a message to the pointer once it's been released. But if I use weak
, this won't ever happen, because message send to nil
won't do anything.
我不知道 strong
和 retain
之间有什么区别.
I don't know about any differences between strong
and retain
.
有什么理由让我在新项目中使用 assign
和 retain
或者是被弃用的那种?
Is there any reason why should I use assign
and retain
in new projects, or are the kind of being deprecated?
推荐答案
来自 过渡到 ARC 发行说明(属性属性部分中的示例).
From the Transitioning to ARC Release Notes (the example in the section on property attributes).
// The following declaration is a synonym for: @property(retain) MyClass *myObject;
@property(strong) MyClass *myObject;
所以 strong
与属性声明中的 retain
相同.
So strong
is the same as retain
in a property declaration.
对于 ARC 项目,我将使用 strong
而不是 retain
,我将使用 assign
用于 C 原始属性和 weak
用于对 Objective-C 对象的弱引用.
For ARC projects I would use strong
instead of retain
, I would use assign
for C primitive properties and weak
for weak references to Objective-C objects.
这篇关于Objective-C ARC:强 vs 保留和弱 vs 分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!