列举的NSArray开始givven指数搜索两种方式(不回绕) [英] Enumerate NSArray starting at givven index searching both ways (no wrap around)

查看:159
本文介绍了列举的NSArray开始givven指数搜索两种方式(不回绕)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为例。我有15个对象的数组。我要开始从给定的索引枚举。说开始于指数5,然后上面的指标之下,上方的指数,等下......我不希望它环绕,而是停下来,继续未开发的方向。

Example. I've got an array with 15 objects. I want to start enumerating from a given index. Say start at index 5 and then the index above, the index under, above, under etc... I don't want it to wrap around, but rather stop and continue in unexplored direction.

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

So the order of indexes in my example would be. 5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0, 11, 12, 13, 14

如何才能做到这一点?

推荐答案

下面是一个更紧凑的实现,不需要创建子阵:

Here's a more compact implementation that doesn't require creating subarrays:

@implementation NSArray (Extensions)

- (void)enumerateFromIndex:(NSUInteger)index goBothWaysUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
{
    BOOL stop = NO;
    for (NSUInteger i = 0; i < self.count && !stop; i++) {
        if (index + i < self.count) {
            block([self objectAtIndex:index + i], index + i, &stop);
        }
        if (i != 0 && !stop && i <= index) {
            block([self objectAtIndex:index - i], index - i, &stop);
        }
    }
}

@end

这篇关于列举的NSArray开始givven指数搜索两种方式(不回绕)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆