gpt4 book ai didi

ios - 有没有办法在 for..in 循环中检查 NSArray 中的下一个对象?

转载 作者:可可西里 更新时间:2023-11-01 05:01:44 25 4
gpt4 key购买 nike

我有这个 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;
}

或者(推荐)用 block 枚举它

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

关于ios - 有没有办法在 for..in 循环中检查 NSArray 中的下一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14611425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com