Reputation: 15857
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
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
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