Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 392
Nick Moore Avatar asked Oct 21 '11 13:10

Nick Moore


2 Answers

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

like image 116
andyvn22 Avatar answered Sep 30 '22 18:09

andyvn22


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.

like image 28
omz Avatar answered Sep 30 '22 20:09

omz