正确使用ARC(自动引用计数)?
创建属性时,将所有 retains
替换为 strong
,将所有 assigns
替换为 weak
是否正确?
我要切换到 ARC 有什么有用的提示吗?
While creating properties, is it correct to replace all retains
with strong
, and all assigns
with weak
?
I'm switching to ARC any helpful tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
阅读过渡到 ARC 发行说明
指南:编辑>重构>转换为 Objective-C ARC。
首先,它可能会报告各种问题(在预检查构建阶段),只需尝试修复所有问题,重试并再次(构建和失败),当所有问题都修复后,最终会顺利完成,留下您的使用 ARC 进行编码。
请注意,预检查规则比通常的构建设置更严格。
Read Transitioning to ARC Release Notes
Use Xcode's guide: Edit > Refactor > Convert to Objective-C ARC.
At first, it may report various issues( in the precheck building phase), just try fixing all issues, try again and (build and fail )again, and it would be done mostly smoothly in the end when all issues are fixed, leaving your code with ARC.
Note that the pre-checking rules are more tough than usual build settings.
据我所知,
strong
和retain
是同义词,因此它们的作用完全相同。编辑:
unsafe_unretained
也是分配
的同义词,正如 nielsbot 指出的那样。然后是
weak code> 几乎类似于
assign
,但在它指向的对象被释放后自动设置为 nil。这意味着,您可以简单地替换它们。
但是,我遇到过一种特殊情况,我必须使用
assign
,而不是weak.假设我们有两个属性
delegateAssign
和delegateWeak
。两者都存储了我们的委托,即通过拥有唯一的强引用来拥有我们。委托正在释放,因此我们的-dealloc
方法也被调用。委托已处于释放过程中,但仍未完全释放。问题是对他的
weak
引用已经无效!属性delegateWeak
包含nil,但是delegateAssign
包含有效对象(所有属性均已释放并作废,但仍然有效)。这是一个非常特殊的情况,但它向我们揭示了这些弱变量如何工作以及它们何时被取消。
As far as I know,
strong
andretain
are synonyms, so they do exactly the same.Edit: Also
unsafe_unretained
is synonym forassign
, as nielsbot pointed out.Then the
weak
is almost likeassign
, but automatically set to nil after the object, it is pointing to, is deallocated.That means, you can simply replace them.
However, there is one special case I've encountered, where I had to use
assign
, rather thanweak
. Let's say we have two propertiesdelegateAssign
anddelegateWeak
. In both is stored our delegate, that is owning us by having the only strong reference. The delegate is deallocating, so our-dealloc
method is called too.The delegate is already in deallocation process, but still not fully deallocated. The problem is that
weak
references to him are already nullified! PropertydelegateWeak
contains nil, butdelegateAssign
contains valid object (with all properties already released and nullified, but still valid).It is quite special case, but it reveal us how those
weak
variables work and when they are nullified.简短的回答是肯定的。
strong
相当于retain
的 ARC,而weak
相当于assign
,只不过它也是归零(如果对象被释放,则将指针设置为nil
,以防止潜在的EXC_BAD_ACCESS
崩溃),因此它甚至比assign
更好。 过渡到 ARC 发行说明页面,如前所述,如果您有兴趣,可以提供更多详细信息。Short answer is yes.
strong
is the ARC equivalent ofretain
, andweak
is the equivalent ofassign
, only it is also zeroing (sets the pointer tonil
if the object is deallocated, preventing potentialEXC_BAD_ACCESS
crashes), so it is even better thanassign
. The Transitioning to ARC Release Notes page, as already mentioned, provides more details if you're interested.