Search code examples
objective-cprefixenumerate

Objective-c enumerateUsingBlock Issue


I want to extract all objects that has prefix "be", but I get only the first object, not all from various indexes. "array" contains various objects, and it contains objects like "be", "become", "beta", "be", "beaver", etc. What is wrong here?

When I use localizedCaseInsensitiveCompare:, it shows only two "be" which is correct in terms of "isEqualToString:" and "array" contains actually two "be" from different indexes.

The codes are as follow:

NSString *string =@"be";

NSRange range = NSMakeRange(0, 24);

NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndexesInRange: range];

[array enumerateObjectsAtIndexes:indexSet options: NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger index, BOOL *stop)

{
    //if([obj localizedCaseInsensitiveCompare:string] == NSOrderedSame)
    if([obj hasPrefix:string])

    {
        NSLog(@"Object Found: %@ at index: %i",obj, index);

        *stop=YES;

    }

} ];

Solution

  • You only get the first because you stop the loop as soon as you find a single result via the *stop = YES line. Remove that.

    You should also use -indexesOfObjectsPassingTest: with your test, then take the returned index set and pass it to -objectsAtIndexes:.