8.9.3 Fast Enumeration Details
Here is a more technical description with the gory details. Consider the code
for (object expression in collection expression)
{
statements
}
here is what happens when you run it:
-
collection expressionis evaluated exactly once and the result is used as the collection object to iterate over. This means it is safe to write code such asfor (object in [NSDictionary keyEnumerator]) …. - the iteration is implemented by the compiler by repeatedly getting batches of objects from the collection object using the fast enumeration protocol (see below), then iterating over all objects in the batch. This is faster than a normal enumeration where objects are retrieved one by one (hence the name “fast enumeration”).
- if there are no objects in the collection, then
object expressionis set toniland the loop immediately terminates. - if there are objects in the collection, then for each object in the collection (in the order they are returned)
object expressionis set to the object, thenstatementsare executed. -
statementscan containbreakandcontinuecommands, which will abort the iteration or skip to the next loop iteration as expected. - when the iteration ends because there are no more objects to iterate over,
object expressionis set tonil. This allows you to determine whether the iteration finished because abreakcommand was used (in which caseobject expressionwill remain set to the last object that was iterated over) or because it iterated over all the objects (in which caseobject expressionwill be set tonil). -
statementsmust not make any changes to the collection object; if they do, it is a hard error and the fast enumeration terminates by invokingobjc_enumerationMutation, a runtime function that normally aborts the program but which can be customized by Foundation libraries viaobjc_set_mutation_handlerto do something different, such as raising an exception.
Next: Fast enumeration protocol, Previous: c99-like fast enumeration syntax, Up: Fast enumeration [Contents][Index]
© Free Software Foundation
Licensed under the GNU Free Documentation License, Version 1.3.
https://gcc.gnu.org/onlinedocs/gcc-8.3.0/gcc/Fast-enumeration-details.html