Fast enumeration over nil object

5.5k Views Asked by At

What should happen here? Is it safe?

NSArray *nullArray=nil;
for (id obj in nullArray) {
  // blah
}

More specifically, do I have to do this:

NSArray *array=[thing methodThatMightReturnNil];
if (array) {
  for (id obj in array) {
    // blah
  }
}

or is this fine?:

for (id obj in [thing methodThatMightReturnNil]) {
  // blah
}
2

There are 2 best solutions below

0
On BEST ANSWER

Nothing will happen. A for-in loop uses the NSFastEnumeration protocol to iterate over the elements in a collection, so you're essentially sending a message to nil which is safe in Objective-C.

0
On

Fast enumeration is implemented through the method - countByEnumeratingWithState:objects:count:, which returns 0 to signal the end of the loop. Since nil returns 0 for any method, your loop should never execute. (So it's safe.)