Nick Moore
Nick Moore

Reputation: 15857

Fast enumeration over nil object

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
}

Upvotes: 44

Views: 5628

Answers (2)

andyvn22
andyvn22

Reputation: 14824

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

Upvotes: 51

omz
omz

Reputation: 53561

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.

Upvotes: 21

Related Questions