如何测试 NSString 是否为零?
我可以简单地使用
if(myString == nil)
出于某种原因,我知道为空的字符串导致此语句失败。
Can I simply use
if(myString == nil)
For some reason a string that I know is null, is failing this statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
似乎调试器中的字符串报告为 (null),但这是由于它的分配方式所致,我修复了它,现在它报告为 nil。 这解决了我的问题。
谢谢!
It seems that my string in the debugger was reporting as (null) but that was due to how it was being assigned, I fixed it and now it is reporting as nil. This fixed my issue.
Thanks!
您可以隐式检查
nil
(已分配,但未初始化):如果
myString
是从字典或数组分配的,您可能还希望检查NSNULL
像这样:最后(正如 Sophie Alpert 提到的),您可以检查空字符串(空值):
通常,您可能想要合并表达式:
You can implicitly check for
nil
(allocated, but not initialized) with this:If
myString
was assigned from a dictionary or array, you may also wish to check forNSNULL
like this:Finally (as Sophie Alpert mentioned), you can check for empty strings (an empty value):
Often, you may want to consolidate the expressions:
我今天遇到了这个问题。 尽管将字符串指定为 nil:
NSString *str = nil;
,测试if (str == nil)
返回FALSE
! 然而,将测试更改为if (!str)
有效。I encountered this problem today. Despite assigning a string to be nil:
NSString *str = nil;
, the testif (str == nil)
returnedFALSE
! Changing the test toif (!str)
worked, however.检查 NSAttributedString 是否为空:
Check NSAttributedString is empty:
有没有可能您的字符串实际上不是
nil
,而只是一个空字符串? 您可以尝试测试是否[myString length] == 0
。Is it possible that your string is not in fact
nil
, and is instead just an empty string? You could try testing whether[myString length] == 0
.您可以在此处找到有关 Objective C 字符串的更多信息。
You can find more on objective C string here.
你可以使用这个检查你的获取字符串
you may check your getting string using this
注意 length = 0 并不一定意味着它是 nil
他们不一样。 虽然两者的长度都是0。
Notice length = 0 doesn't necessary mean it's nil
They are not the same. Although both the length are 0.