枚举NSArray从给定索引开始搜索两种方式(没有环绕)

时间:2013-01-15 15:51:51

标签: ios arrays nsarray enumeration

实施例。我有一个包含15个对象的数组。我想从给定的索引开始枚举。比如说从索引5开始,然后是上面的索引,索引在下面,上面,下面等...我不想让它环绕,而是停下来继续未开发的方向。

所以我的例子中的索引顺序是。 5,6,4,7,3,8,2,9,1,10,0,11,12,13,14

如何做到这一点?

2 个答案:

答案 0 :(得分:1)

-(void)enumerateArray:(NSArray *)array inBothDirectionsFromIndex:(int)startIndex
{
    for (int i=0; i<array.count; i++)
    {
        int index = startIndex;
        int indexAfter = startIndex + round(i/2.f) + (i%2 ? 0 : 1);
        int indexBefore = startIndex - round(i/2.f);

        if ((i%2 && indexAfter < array.count) || indexBefore < 0)
        {
            index = indexAfter;
            if (indexBefore < 0)
                index -= indexBefore + 1;
        }
        else if ((i > 0 && indexBefore > -1) || indexAfter > array.count-1)
        {
            index = indexBefore;
            if (indexAfter > array.count-1)
                index -= indexAfter - array.count;;
        }

        id item = [array objectAtIndex:index];

        //Do what you want with the item here

    }
}

答案 1 :(得分:0)

它回答了这个问题,但并不特别干,创建子阵列使其效率低于应有的水平。

@implementation NSArray (Extensions)

- (void)enumerateFromIndex:(NSUInteger)index goBothWaysUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
{
    NSArray *lastObjects = [self subarrayFromIndex:index];
    NSArray *firstObjects = [self subarrayToIndex:index];
    int currentIndex = 0;

    NSEnumerator *firstObjectsEnumerator = [firstObjects reverseObjectEnumerator];
    NSEnumerator *lastObjectsEnumerator = [lastObjects objectEnumerator];
    BOOL shouldStop = NO;
    NSUInteger numberOfIndexesEnumerated = 0;
    id obj = nil;

    while(numberOfIndexesEnumerated < self.count)
    {
        if (obj = [lastObjectsEnumerator nextObject])
        {
            NSInteger objIndex = [self indexOfObject:obj];
            block(obj, objIndex, &shouldStop);
            currentIndex++;
            numberOfIndexesEnumerated++;
        }
        if (shouldStop)
        {
            return;
        }

        if (obj = [firstObjectsEnumerator nextObject])
        {
            NSInteger objIndex = [self indexOfObject:obj];
            block(obj, objIndex, &shouldStop);
            currentIndex++;
            numberOfIndexesEnumerated++;
        }
        if (shouldStop)
        {
            return;
        }
    }
}

@end

回答@jalmaas的回答