Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is __strong required in fast enumeration loops with ARC

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]
    }
}

Fast Enumeration variables cannot be modified in ARC: declare __strong

What does __strong do and why must I add it?

like image 831
James Dunay Avatar asked Dec 07 '22 05:12

James Dunay


1 Answers

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

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.

like image 169
Gabriele Petronella Avatar answered Dec 08 '22 19:12

Gabriele Petronella