44

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
}
Nick Moore
  • 15,547
  • 6
  • 61
  • 83
  • 5
    @JeremyP: I almost said that myself, but it's nice to know not only that it happens to work, but that it works by design, there are implementation-independent reasons it works, and it's likely to continue to work in future versions of OS X. – andyvn22 Oct 21 '11 at 13:27
  • 2
    @JeremyP Seriously. I already did that before I asked the question, and it worked with no errors. But it proves nothing because it could have been a fluke. I was looking for the theory behind it. – Nick Moore Oct 21 '11 at 15:18

2 Answers2

51

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.)

andyvn22
  • 14,696
  • 1
  • 52
  • 74
21

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.

omz
  • 53,243
  • 5
  • 129
  • 141