Search code examples
objective-cfor-loopfast-enumeration

Strange for loops I'm not familiar with: "for (id * in *)"


I apologize if this question is exceedingly simple, but I've Googled like crazy and am unable to find a suitable explanation for what this is.

for (id line in self.lines){
    [linesCopy addObject:[line copyWithZone:zone]];
}

I'm just learning Objective-C, and this is a form of for loop that I've never seen before. I'm familiar with the simple

for (int x = 1, x < 10, x++)

style of for loop.


Solution

  • From Cocoa Core Competencies: Enumeration:

    Fast Enumeration

    Several Cocoa classes, including the collection classes, adopt the NSFastEnumeration protocol. You use it to retrieve elements held by an instance using a syntax similar to that of a standard C for loop, as illustrated in the following example:

    NSArray *anArray = // get an array;
    for (id element in anArray) {
        /* code that acts on the element */
    }
    

    As the name suggests, fast enumeration is more efficient than other forms of enumeration.

    In case you didn't know, id is an Objective-C type that basically means “a pointer to any Objective-C object”. Note that the pointer-ness of id is built in to it; you usually do not want to say id *.

    If you expect the elements of anArray to be of a specific class, say MyObject, you can use that instead:

    for (MyObject *element in anArray) {
        /* code that acts on the element */
    }
    

    However, neither the compiler nor the runtime will check that the elements are indeed instances of MyObject. If an element of anArray is not an instance of MyObject, you'll probably end up trying to send it a message it doesn't understand, and get a selector-not-recognized exception.