Cocoa:while(index> = 0)继续,即使index == -1

fre*_*oma 0 macos cocoa objective-c while-loop

我有以下代码:

-(void)removeFilesWithPathIndices:(NSIndexSet*)indexSet {
    NSInteger index = [indexSet firstIndex];
    while(index >= 0) {
        [self removeFileWithPathIndex:index];
        index = [indexSet indexGreaterThanIndex:index];
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个应该遍历NSIndexSet.但是,即使index = -1,while循环也不会停止

 NSLog(@"%d", index);
Run Code Online (Sandbox Code Playgroud)

有谁能为我解决这个谜团?:)

Yuj*_*uji 10

不要以为NSIntegerint.事实上并非如此.所以,%d

NSLog(@"%d", index);
Run Code Online (Sandbox Code Playgroud)

如果你在64位模式下编译,就会欺骗你.请参阅NSInteger文档.

你甚至不应该假设indexGreaterThanIndex要回来-1.文档明确说明它返回NSNotFound.通过下面的文档,你最终会发现NSNotFound就是NSIntegerMax,在可能的最高值NSInteger.什么时候NSIntegerlong投入int,他就变成了-1.但这是一个实现细节,你不应该依赖它.这就是为什么他们开始定义一个符号常量NSNotFound.

您应该遵循文档所说的内容,并编写类似的代码

while(index != NSNotFound) {
    [self removeFileWithPathIndex:index];
    index = [indexSet indexGreaterThanIndex:index];
}
Run Code Online (Sandbox Code Playgroud)

从某种意义上说,你甚至不应该宣称

NSInteger index;
Run Code Online (Sandbox Code Playgroud)

因为在基金指数均NSüInteger.


chr*_*ssr 5

indexGreatherThanIndex:NSNotFound当没有任何大于指定的索引时返回.Apple文档

NSNotFound定义为NSIntegerMax,即>= 0.Apple文档

你的NSLog陈述只是给你一个欺骗性的结果.代替:

while(index >= 0)
Run Code Online (Sandbox Code Playgroud)

使用:

while(index != NSNotFound)
Run Code Online (Sandbox Code Playgroud)