代码之家  ›  专栏  ›  技术社区  ›  fresskoma

cocoa:当(index>=0)继续时,即使index=-1

  •  0
  • fresskoma  · 技术社区  · 14 年前

    我有以下代码:

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

    它应该遍历nsindexset。但是,while循环不会停止,即使根据

     NSLog(@"%d", index);
    

    有人能帮我解决这个迷雾吗?:)

    2 回复  |  直到 12 年前
        1
  •  10
  •   Yuji    14 年前

    不要假设 NSInteger 成为一个 int . 其实不是。所以, %d 在里面

    NSLog(@"%d", index);
    

    如果在64位模式下编译,会欺骗您。见 NSInteger 文档。

    你甚至不应该假设 indexGreaterThanIndex 归来 -1 . 文件明确指出它返回 NSNotFound . 通过跟踪文档,您最终会发现 NSnNoDebug NSIntegerMax ,中的最大可能值 NS-整型 . 什么时候? NS-整型 long 并铸造成一个 int 他的成为 - 1 . 但这是一个实现细节,您不应该依赖它。这就是为什么他们定义了一个符号常量 NSnNoDebug 首先。

    您应该遵循文档中的说明,编写类似这样的代码

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

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

    NSInteger index;
    

    因为基金会的指数都是 NS U Integer .

        2
  •  5
  •   chrissr    14 年前

    indexGreatherThanIndex: 收益率 NSNotFound 当没有大于指定索引的内容时。 Apple Documentation

    NSnNoDebug 定义为 NSIntegerMax ,这就是 >= 0 . Apple Documentation

    你的 NSLog 声明只是给你一个欺骗性的结果。而不是:

    while(index >= 0)
    

    用途:

    while(index != NSNotFound)