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

时间:2013-08-22 17:40:49

标签: ios objective-c xcode automatic-ref-counting

当我做类似以下的事情时,我收到错误说

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

Fast Enumeration variables cannot be modified in ARC: declare __strong

__strong做了什么以及为什么要添加它?

2 个答案:

答案 0 :(得分:15)

  

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

     

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

source

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

在迭代数组时对数组进行变换在任何情况下都是一个坏主意。只需在迭代时构建一个新数组,你就可以了。

答案 1 :(得分:0)

为什么要为该指针分配新值?您是否尝试替换阵列中的对象?在这种情况下,您需要在集合中保存要替换的内容并在枚举之外执行,因为在枚举时不能改变数组。

NSMutableDictionary * viewsToReplace = [[NSMutableDictionary alloc] init];
NSUInteger index = 0;

for(UIView * view in bottomAttachments){
    if (i <= [cells count]) {
        // Create your new view
        UIView * newView = [[UIView alloc] init];
        // Add it to a dictionary using the current index as a key
        viewsToReplace[@(index)] = newView;
    }
    index++;
}

// Enumerate through the keys in the new dictionary
// and replace the objects in the original array
for(NSNumber * indexOfViewToReplace in viewsToReplace){
    NSInteger index = [indexOfViewToReplace integerValue];
    UIView * newView = viewsToReplace[indexOfViewToReplace];
    [array replaceObjectAtIndex:index withObject:newView];
}