Objective-C字符串比较

Rob*_*the -1 objective-c

我有一系列名称,但似乎无法使比较工作.我在这里使用不当的语言吗?

NSLog(@"%@",[arrayOfNames objectAtIndex:0]);

if ([arrayOfNames objectAtIndex:0] == "Blue"){ 
  NSLog(@"it's Blue");
}
else {
  NSLog(@"it's not Blue");
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

蓝色

它不是蓝色的

xCo*_*der 7

使用以下内容:

if ([[arrayOfNames objectAtIndex:0] isEqualToString:@"Blue"])
Run Code Online (Sandbox Code Playgroud)

您正在使用==运算符比较两个对象(其中一个是id-type,另一个是C-string).比较将失败,因为它们是2个不同的对象.使用isEqualToString,您将对象的值与字符串进行比较@"Blue".

  • 甚至没有两个物体; `"Blue"`是一个C字符串,而不是Objective-C对象. (2认同)