为什么字符串比较返回true?
问题描述:
可能重复:
Comparing Strings in Cocoa
Why is this code not recognising the NSString as being equal?为什么字符串比较返回true?
我有一个值的设定NSUserDefaults的向@ “YES”。当我运行这个方法...
- (void) checkForHint {
NSLog(@"call:checkForHint");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(@"valueForKeyInDefaults:%@",[defaults valueForKey:@"giveHint"]);
if ([defaults valueForKey:@"giveHint"] == @"YES") {
NSLog(@"need to give hint");
// replace a letter at random
int i=0;
bool found = NO;
while (!found && i<NUM_CHARACTERS_IN_LEVEL_STRING) {
NSLog(@"searching at index %i",i);
if ([buttons objectAtIndex:i] && 32==[[levelSavedSolutionArray objectAtIndex:i] intValue]) {
found = YES;
}
i++;
}
i--;
// We need to select all the buttons at this unsolved space
[self buttonClicked:[buttons objectAtIndex:i]];
// update the entries in all selected buttons
[self keyAct:[[levelStringArray objectAtIndex:i] intValue]];
}
}
输出到控制台:
2012-03-28 23:11:41.799 (APPID) call:checkForHint
2012-03-28 23:11:41.800 (APPID) valueForKeyInDefaults:YES
我不明白为什么这个if语句心不是返回true .. 任何人谁可以帮助将不胜赞赏。我有一种感觉,因为两个字符串是不同的实例,碰巧有相同的值,但我不知道如何解决这个问题。
答
操作==在这种情况下比较指针。很明显,您正在比较两个不同的对象:@"YES"
这是一个文字字符串,而对象是由方法调用返回的[defaults valueForKey:@"giveHint"]
。
如果你需要他们的内容使用[[defaults valueForKey:@"giveHint"] isEqualToString:@"YES"]
+0
谢谢。很好的回答! – bkbeachlabs 2012-03-29 05:19:02
计数器的问题比较字符串:**为什么''==被用于*字符串* **比较搜索重复,你会发现他们..? 。在任何情况下,Objective-C *都没有*操作符重载,这就是为什么'=='不能可靠地为两个NSObject的*值相等*工作。 – 2012-03-29 03:18:23
对不起,我真的不知道要搜索什么。有比较字符串的具体方法吗?谢谢 – bkbeachlabs 2012-03-29 03:20:03
搜索“compare nsstrring”或“equals nsstring”。 – 2012-03-29 03:20:53