检查if(country == @“(null)”是否有效

时间:2010-03-31 15:30:46

标签: iphone null if-statement

我遇到了if语句不起作用的问题。在第一个代码行之后,变量包含值“(null)”,因为从他的iphone地址簿中选择联系人的用户没有为此联系人设置国家/地区密钥,到目前为止一直很好。

但是如果我检查变量,它就不会是真的,但是值肯定是“(null)”......有人有想法吗?

 NSString *country = [NSString [the dict objectForKey:(NSString *)kABPersonAddressCountryKey]];

 if(country == @"(null)")
 {
      country = @"";
 }
提前谢谢你 肖恩

2 个答案:

答案 0 :(得分:5)

正确的表达方式是:

if (country == nil)

可以进一步缩短为:

if (!country)

如果你真的想用@"(null)"字符串测试相等性,你应该使用isEqual:方法或isEqualToString:

if ([country isEqualToString:@"(null)"])

使用==运算符进行比较时,您要比较对象地址,而不是它们的内容:

NSString *foo1 = [NSString stringWithString:@"foo"];
NSString *foo2 = [NSString stringWithString:@"foo"];
NSAssert(foo1 != foo2, @"The addresses are different.");
NSAssert([foo1 isEqual:foo2], @"But the contents are same.");
NSAssert([foo1 isEqualToString:foo2], @"True again, faster than isEqual:.");

答案 1 :(得分:-2)

这是一个很好的答案我不知道有没有检查nil或null字符串的所有不同方法。

相关问题