为什么在使用ARC的快速枚举循环中需要__strong [英] Why is __strong required in fast enumeration loops with ARC

查看:224
本文介绍了为什么在使用ARC的快速枚举循环中需要__strong的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做同样的事情时,我得到一个错误说

When I do something simialr to the following I get an error saying

for (UIView* att in bottomAttachments) {
    if (i <= [cells count]) {
        att = [[UIView alloc] extraStuff]
    }
}

无法在ARC中修改快速枚举变量:声明__strong

__ strong 做什么以及为什么要添加它?

What does __strong do and why must I add it?

推荐答案


如果在Objective-C快速枚举循环的条件下声明变量,并且变量没有显式的所有权限定符,则它使用 const进行限定__strong 和枚举期间遇到的对象实际上没有保留。

If a variable is declared in the condition of an Objective-C fast enumeration loop, and the variable has no explicit ownership qualifier, then it is qualified with const __strong and objects encountered during the enumeration are not actually retained.

理由

这是一种可能的优化,因为快速枚举循环允许在枚举期间保留对象,并且集合本身不能是sy经过同步修改。可以通过使用 __ strong 显式限定变量来覆盖它,这将使变量再次变为可变并导致循环保留它遇到的对象。

Rationale
This is an optimization made possible because fast enumeration loops promise to keep the objects retained during enumeration, and the collection itself cannot be synchronously modified. It can be overridden by explicitly qualifying the variable with __strong, which will make the variable mutable again and cause the loop to retain the objects it encounters.

source

正如Martin在评论中指出的那样,值得注意的是,即使使用 __ strong 变量,通过重新分配给你不会修改数组本身,但你只需要将局部变量指向另一个对象。

As Martin noted in a comment, it's worth noting that even with a __strong variable, by reassigning it you won't modify the array itself, but you'll just make the local variable point to a different object.

在迭代数组时改变数组通常是一个坏主意任何状况之下。只需在迭代时构建一个新数组,你就可以了。

Mutating an array while iterating on it is generally a bad idea in any case. Just build a new array while iterating and you'll be fine.

这篇关于为什么在使用ARC的快速枚举循环中需要__strong的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆