在for..in循环中,有没有一种方法可以检查NSArray中的下一个对象?

4

我有一个NSArray:

NSArray* temp=[[NSArray alloc]
initWithObjects:@"one",@"five",@"two",nil];

for(NSString* obj in temp){ 
    NSLog(@"current item:%@ Next item is:%@",obj, ***blank***);
}

需要将空白替换为什么?我是否需要知道即将到来的对象?


2
快速枚举是解决单一特定问题的方法,如果您需要更复杂的行为,我相信您必须回到传统的循环,并简单地使用索引+1来获取下一个对象。 - T. Benjamin Larsen
你可以在普通的for循环中根据索引获取数据。如果[temp count]>(currentIndex+1),则获取[temp objectAtIndex:[currentIndex+1]]的数据。 - Reno Jones
@rmaddy - 是的,这就是为什么我提到了 If [temp count]>(currentIndex+1) :) - Reno Jones
@RenoJones 抱歉,我理解能力有误 - 对不起 ;) - rmaddy
5个回答

11

只有当你的对象是唯一的(即数组中没有相同的对象)时,才能使用此方法:

id nxt = nil;
int nxtIdx = [temp indexOfObject:idx] + 1;
if (nxtIdx < temp.count) {
    nxt = [temp objectAtIndex:nxtIdx];
}
NSLog(@"current item:%@ Next item is:%@", obj, nxt);

但在我看来,这是一个 hack。为什么不使用带有对象索引的普通 for 循环:

for (int i = 0; i < temp.count; i++) {
    id obj = [temp objectAtIndex:i];
    id next = (i + 1 < temp.count) ? [temp objectAtIndex:i + 1] : nil;
}

或者(推荐)使用块枚举它

[temp enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    id next = nil;
    if (idx + 1 < temp.count) {
        next = [temp objectAtIndex:idx + 1];
    }
}];


3
尝试使用 NSEnumerator
代码:
NSEnumerator *enumerator = [temp objectEnumerator];
id obj;
while (obj = [enumerator nextObject]) {
    if ([enumerator nextObject] == nil) {
       NSLog(@"This is the last object: %@", obj);
       break;
    }
    NSLog(@"current item:%@ Next item is:%@", obj, [enumerator nextObject]);
}

2

如果不添加额外的代码(推导索引、加上它、检查是否仍在范围内),使用快速枚举无法完成此操作。

您可以使用块进行枚举,并将1添加到idx参数,但更好的设计是记住前一个对象,这在第一次迭代时将为nil,从而避免了越界异常的风险或需要检查。


1
您可以通过以下类似的方式获取当前对象的索引并查看下一个对象:
NSArray* temp=[[NSArray alloc] initWithObjects:@"one",@"five",@"two",nil];

for(NSString* obj in temp){

    if([temp count] < [temp indexOfObject:obj]+1)
    {
        NSLog(@"current item:%@ Next item is:%@",obj, [temp objectAtIndex:[temp indexOfObject:obj] + 1]);
    }

}

在这种情况下,有时候使用传统的for循环更容易,因为可以访问索引变量。


0

使用快速枚举,这是唯一的方法:

NSInteger index = [temp indexOfObject:obj];
if (index != NSNotFound && index < temp.count)
    NSObject nextObject = [temp objectAtIndex:(index + 1)];

请注意 if 语句,确保您获得有效的索引,并且将其加一不会越界。

这段代码是错误的!如果 obj 位于一个包含 10 个元素的数组中的索引 9 处(count=10),那么 nextObject 就越界了!它不存在!请使用被接受的答案。为什么不提供完整的答案呢? - Vassilis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接