加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 为什么在使用ARC的快速枚举循环中需要__strong

发布时间:2020-12-14 18:55:24 所属栏目:百科 来源:网络整理
导读:当我做下面的事情时,我得到一个错误说 for (UIView* att in bottomAttachments) { if (i = [cells count]) { att = [[UIView alloc] extraStuff] }} 无法在ARC中修改快速枚举变量:声明__strong __strong做了什么以及为什么要添加它? 解决方法 If a variabl
当我做下面的事情时,我得到一个错误说

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

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

__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.

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变量,通过重新分配它你也不会修改数组本身,但是你只需要将局部变量指向另一个对象.

在迭代数组时对数组进行变换通常是一个坏主意.只需在迭代时构建一个新数组,你就可以了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读