Is the value of the loop variable in a for - in
loop guaranteed to be nil
after the loop executes, as long as the loop does not contain a break
statement? For example, I'd like to write code like the following:
NSArray *items;
NSObject *item;
for (item in items) {
if (item matches some criterion) {
break;
}
}
if (item) {
// matching item found. Process item.
}
else {
// No matching item found.
}
But this code depends on item
being set to nil
when the for
loop runs all the way through with no break
.
You should instead use this:
id correctItem = nil;
for (id item in items) {
if (item matches some criteria) {
correctItem = item;
break;
}
}