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

Sea*_*ean 1 iphone null if-statement

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

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

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

 if(country == @"(null)")
 {
      country = @"";
 }
Run Code Online (Sandbox Code Playgroud)

谢谢提前
肖恩

zou*_*oul 5

正确的表达方式是:

if (country == nil)
Run Code Online (Sandbox Code Playgroud)

可以进一步缩短为:

if (!country)
Run Code Online (Sandbox Code Playgroud)

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

if ([country isEqualToString:@"(null)"])
Run Code Online (Sandbox Code Playgroud)

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

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:.");
Run Code Online (Sandbox Code Playgroud)