从给定索引搜索开始以双向方式枚举NSArray(环绕) [英] Enumerate NSArray starting at givven index searching both ways (wrap around)

查看:81
本文介绍了从给定索引搜索开始以双向方式枚举NSArray(环绕)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例。我有一个包含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 do want it to wrap around.

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

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

一种类似于以下代码行的方法签名,但我不要求批准一个答案:

It would be great to have a method signature similar to following line, but I don't require that to approva an answer:

- (void)enumerateFromIndex:(NSUInteger)index wrapAroundAndGoBothWays:(void (^)(id obj, NSUInteger idx, BOOL *stop))block

这怎么办?希望避免复制数组等。

How can this be done? Would like to avoid copying array etc.

在本文中,我们做到不环绕从givven索引开始枚举NSArray两种方式都进行搜索(无回绕)

At this post we do it with no wrap around: Enumerate NSArray starting at givven index searching both ways (no wrap around)

推荐答案

从@omz借用,这是包装的变体,它甚至更简单:

Borrowing from @omz, here is the wrapping variant, which is even simpler:

@implementation NSArray (Extensions)

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

@end

这篇关于从给定索引搜索开始以双向方式枚举NSArray(环绕)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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