我有一个NSArray:
NSArray* temp=[[NSArray alloc]
initWithObjects:@"one",@"five",@"two",nil];
for(NSString* obj in temp){
NSLog(@"current item:%@ Next item is:%@",obj, ***blank***);
}
需要将空白
替换为什么?我是否需要知道即将到来的对象?
我有一个NSArray:
NSArray* temp=[[NSArray alloc]
initWithObjects:@"one",@"five",@"two",nil];
for(NSString* obj in temp){
NSLog(@"current item:%@ Next item is:%@",obj, ***blank***);
}
需要将空白
替换为什么?我是否需要知道即将到来的对象?
只有当你的对象是唯一的(即数组中没有相同的对象)时,才能使用此方法:
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];
}
}];
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]);
}
如果不添加额外的代码(推导索引、加上它、检查是否仍在范围内),使用快速枚举无法完成此操作。
您可以使用块进行枚举,并将1添加到idx
参数,但更好的设计是记住前一个对象,这在第一次迭代时将为nil,从而避免了越界异常的风险或需要检查。
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循环更容易,因为可以访问索引变量。
使用快速枚举,这是唯一的方法:
NSInteger index = [temp indexOfObject:obj];
if (index != NSNotFound && index < temp.count)
NSObject nextObject = [temp objectAtIndex:(index + 1)];