iosobjective-cif-statementlogical-operatorsnsindexset

Objective C Logical OR operator not evaluating in block


I am trying to check which array element's values are equal to each other or to the NSNumber 10. The array has count 15. The problem is that when I test the value against NSNumber 10 in an if statement, the code does not seem to evaluate.

In the array below, for example, the code should return that the value in index 0 is present in indices {0, 9, 10} since NSNumber 1 is present in index 0 and 10 and NSNumber 10 is present at index 9.

1-2-3-4-5-6-7-8-9-10-1-2-3-4-5

However, it only evaluates whether the NSNumber value in index 0 is equal to NSNumber 1 and not to NSNumber 10. The output is not as expected {0, 9, 10} but only {0, 10}.

for (NSNumber *number in mutableArray) {
    self.matchingIndex = [mutableArray indexesOfObjectsPassingTest:
                         ^BOOL(NSNumber *obj, NSUInteger idx, BOOL *stop) 
    {
        BOOL returnValue;
        NSNumber *ten = [NSNumber numberWithInt:10];
        if ([number isEqualToNumber:obj] || [number isEqualToNumber:ten])
        {
            returnValue = TRUE;
        }
        return returnValue;  
    }];
    [self testIndexSet:self.matchingIndex];
}     

Solution

  • Your expectation is incorrect. number, the outer loop iterator will be equal to ten only for the @10 element in the array. The expected result for the loop is two indexes on the 1..5 elements, and one index for the rest.

    If you'd like the loop to find the @10 element and include that with every result, change the condition from...

    if ([number isEqualToNumber:obj] || [number isEqualToNumber:ten])
    

    to...

    if ([number isEqualToNumber:obj] || [obj isEqualToNumber:ten])
    

    Incidentally, the block can be stated more simply as...

    NSIndexSet *matchingIndex = [mutableArray indexesOfObjectsPassingTest:^BOOL(NSNumber *obj, NSUInteger idx, BOOL *stop) {
        return ([number isEqualToNumber:obj] || [obj isEqualToNumber:@10]);
    }];