The value of the loop variable after the "for in" loop in Objective-C

Is the value of the loop variable in the loop a for - inguarantee nilafter the loop is executed if the loop does not contain an instruction break? For example, I would like to write code as follows:

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 the itemone set in nilwhen the loop forworks completely without break.

+2
source share
3 answers

Instead, you should use this:

id correctItem = nil;
for (id item in items) {
    if (item matches some criteria) {
        correctItem = item;
        break;
    }
}
+1
source

, . , , , . , indexesOfObjectsPassingTest: .

NSUInteger index = [items indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    if (/* check the item*/) {
        *stop = YES;
    }
}];

if (index == NSNotFound) {
    // no match was found
} else {
    // at least one item matches the check
    id match = items[index];
}
+2

If ARC is enabled, your Objective-C object pointer variables will be set to zero regardless of where you create them. [Source]

If you are not using ARC, you can explicitly point to nil:

NSArray *items;
NSObject *item = nil;  //<- Explicitly set to nil
for (item in items) {
   if (item matches some criterion) {
      break;
   }
}
if (item) {
   // matching item found. Process item.
}
else {
   // No matching item found.
}

I don’t know the specific case, but could you just do this by doing the work inside the for loop:

NSArray *items;
NSObject *item; //Doesn't really matter about item being set to nil here.
for (item in items) {
   if (item matches some criterion) 
   {
       // matching item found. Process item.
      break;
   }
}
//Don't have to worry about item after this
+1
source

Source: https://habr.com/ru/post/1648294/


All Articles