4

当我做与以下类似的事情时,我收到一条错误消息

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

Fast Enumeration variables cannot be modified in ARC: declare __strong

做什么__strong,为什么我必须添加它?

4

2 回答 2

15

如果在 Objective-C 快速枚举循环的条件下声明了一个变量,并且该变量没有明确的所有权限定符,那么它被限定为,const __strong并且在枚举期间遇到的对象实际上并没有被保留。

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

资源

正如 Martin 在评论中指出的那样,值得注意的是,即使使用__strong变量,通过重新分配它也不会修改数组本身,而只会使局部变量指向不同的对象。

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

于 2013-08-22T17:45:22.183 回答
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];
}
于 2013-08-22T18:04:02.347 回答