objective-c - cocoa : while(index >= 0) 继续,即使index == -1

标签 objective-c cocoa macos while-loop

我有以下代码:

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

它应该迭代 NSIndexSet。然而, while 循环不会停止,即使根据

索引 = -1
 NSLog(@"%d", index);

谁能帮我解开这个谜团? :)

最佳答案

不要假设 NSIntegerint。事实上并非如此。因此,%d

NSLog(@"%d", index);

如果你在64位模式下编译,那是在欺骗你。请参阅NSInteger文档。

您甚至不应该假设 indexGreaterThanIndex 返回 -1。 文档明确表示它返回 NSNotFound。通过遵循文档,您最终会发现 NSNotFoundNSIntegerMax,即 NSInteger 中的最大可能值。当 NSIntegerlong 并转换为 int 时,他的变为 -1。但这是一个实现细节,您不应该依赖它。这就是为什么他们首先定义了一个符号常量 NSNotFound

您应该遵循文档的说明,并编写如下代码

while(index != NSNotFound) {
    [self removeFileWithPathIndex:index];
    index = [indexSet indexGreaterThanIndex:index];
}

从某种意义上说,你甚至不应该声明

NSInteger index;

因为Foundation中的索引都是NSUInteger

关于objective-c - cocoa : while(index >= 0) 继续,即使index == -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3258745/

相关文章:

java - 为什么 Grails 在 Mac OS x 7 上使用旧的 JVM 编译器?

ruby - "Pow is installed"现在出现在我所有的网站上

ios - 对两个项目使用水平滚动时右对齐 UICollectionView(对于 RTL)

objective-c - 使用另一种语言的 Iphone 可本地化字符串

objective-c - 如何切换 NSSplitView subview 的可见性 + 隐藏 Pane Splitter 分隔符?

iphone - UITabBar 中选定的 View

cocoa - 将 subview 添加到 NSView 以获得类似国际象棋的网格

python - 当我尝试在 Mac mojave 10.14 中安装 MySQL-python 包时出现错误 : command 'cc' failed with exit status 1.

ios - 定义与以前的值冲突 - Xcode 6.3.2

iphone - UITableViewController 背景图片