我有以下代码:
-(void)removeFilesWithPathIndices:(NSIndexSet*)indexSet {
NSInteger index = [indexSet firstIndex];
while(index >= 0) {
[self removeFileWithPathIndex:index];
index = [indexSet indexGreaterThanIndex:index];
}
}
它应该迭代 NSIndexSet。然而, while 循环不会停止,即使根据
索引 = -1 NSLog(@"%d", index);
谁能帮我解开这个谜团? :)
最佳答案
不要假设 NSInteger
是 int
。事实上并非如此。因此,%d
在
NSLog(@"%d", index);
如果你在64位模式下编译,那是在欺骗你。请参阅NSInteger文档。
您甚至不应该假设 indexGreaterThanIndex
返回 -1
。
文档明确表示它返回 NSNotFound
。通过遵循文档,您最终会发现 NSNotFound
是 NSIntegerMax
,即 NSInteger
中的最大可能值。当 NSInteger
为 long
并转换为 int
时,他的变为 -1
。但这是一个实现细节,您不应该依赖它。这就是为什么他们首先定义了一个符号常量 NSNotFound
。
您应该遵循文档的说明,并编写如下代码
while(index != NSNotFound) {
[self removeFileWithPathIndex:index];
index = [indexSet indexGreaterThanIndex:index];
}
从某种意义上说,你甚至不应该声明
NSInteger index;
因为Foundation中的索引都是NS
UInteger
。
关于objective-c - cocoa : while(index >= 0) 继续,即使index == -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3258745/