FOR命令中的表达式(for(int i = 0; i <([arr count] -1); i ++){})

Ton*_*ony 6 objective-c ios

我有一个我无法理解的问题

NSArray *emptyArr = @[];
for (int i=0; i < ([emptyArr count]-1) ; i++) {
    NSLog(@"Did run for1");
}
Run Code Online (Sandbox Code Playgroud)

[emptyArr count]- 1是-1但我的应用程序仍然运行NSLog命令!

如果我使用int变量:

NSArray *emptyArr = @[];
int count = [emptyArr count]-1;
for (int i=0; i < count ; i++) {
    NSLog(@"Did run for1");
}
Run Code Online (Sandbox Code Playgroud)

然后我的应用程序不运行NSLog命令.

有人帮我请!

bor*_*den 6

这是因为返回类型count无符号的 int.当你从0减去1时,你得不到-1.相反,你可以尽可能地下流unsigned int.它在第二个版本中工作的原因是因为您(隐式)将int其转换为值-1合法的值.