检查 if(country == @"(null)" 不起作用

发布于 2024-08-27 10:06:42 字数 345 浏览 3 评论 0 原文

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

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

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

 if(country == @"(null)")
 {
      country = @"";
 }

提前致谢
肖恩

I got the problem that the if-statement doesn't work. After the first code line the variable contains the value "(null)", because the user who picked the contact from his iphone address book doesn't set the country key for this contact, so far so good.

but if I check the variable, it won't be true, but the value is certainly "(null)"... does someone have an idea?

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

 if(country == @"(null)")
 {
      country = @"";
 }

thanks in advance
sean

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

画尸师 2024-09-03 10:06:42

正确的表达式是:

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:.");

The correct expression would be:

if (country == nil)

which can be further shortened to:

if (!country)

And if you really want to test equality with the @"(null)" string, you should use the isEqual: method or isEqualToString:

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

When you compare using the == operator, you are comparing object addresses, not their contents:

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:.");
知足的幸福 2024-09-03 10:06:42

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

That was a great answer I didn't know there was all those different ways of checking for nil or null string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文