4

我有这个 NSArray:

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

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

需要更换blank什么?我需要知道即将到来的对象吗?

4

5 回答 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);

但在我看来,这是一个黑客。为什么不使用带有对象索引的普通 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];
    }
}];

于 2013-01-30T18:52:05.337 回答
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]);
}
于 2013-01-30T18:49:18.377 回答
2

如果没有几行额外代码(导出索引、添加索引、检查其是否仍在边界内),您无法通过快速枚举来做到这一点。

您可以使用块进行枚举并将一个添加到idx参数中,但更好的设计(您不会冒险或不必检查越界异常)将记住前一个对象,这将是您的第一个对象迭代。

于 2013-01-30T18:51:06.273 回答
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 循环有时会更容易访问您的索引变量。

于 2013-01-30T18:49:03.130 回答
0

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

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

请注意如果,您需要确保获得一个有效的索引,并且向其中添加一个不会让您越界。

于 2013-01-30T18:49:32.630 回答