Search code examples
iosobjective-cnsarrayenumeration

Enumerate NSArray starting at center / middle of array searching both ways


How can I enumerate an array starting at the center of the array?


Solution

  • @implementation NSArray (Extensions)
    
    - (void)enumerateFromCenterGoBothWaysUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
    {
        NSMutableArray *copy = [self mutableCopy];
        BOOL shouldStop = NO;
        while([copy count] > 0 && shouldStop == NO)
        {
            NSUInteger index = [copy count] / 2;
            id obj = copy[index];
            [copy removeObject:obj];
    
            block(obj, index, &shouldStop);
        }
    }
    
    @end