在 Objective-C 中检查空字符串的正确方法是什么? [英] What is the right way to check for a null string in Objective-C?
问题描述
我在我的 iPhone 应用程序中使用了这个
I was using this in my iPhone app
if (title == nil) {
// do something
}
但它抛出了一些异常,并且控制台显示标题为(空)".
but it throws some exception, and the console shows that the title is "(null)".
所以我现在正在使用它:
So I'm using this now:
if (title == nil || [title isKindOfClass:[NSNull class]]) {
//do something
}
有什么区别,判断一个字符串是否为空的最好方法是什么?
What is the difference, and what is the best way to determine whether a string is null?
推荐答案
正如其他人所指出的,在 Cocoa/Objective C 下有很多种null".但还有一点需要注意的是 [title isKindOfClass:[NSNull 类]] 毫无意义地复杂,因为 [NSNull null] 被记录为单例,因此您可以只检查指针是否相等.请参阅 Cocoa 主题:使用 Null.
As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.
所以一个好的测试可能是:
So a good test might be:
if (title == (id)[NSNull null] || title.length == 0 ) title = @"Something";
请注意,即使title 为nil,title.length 也将返回0/nil/false,即在这种情况下为0,因此您不必对它进行特殊处理,请注意如何使用这一事实.这是Objective C的新手很难习惯的东西,尤其是从消息/方法调用nil崩溃的其他语言而来.
Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.
这篇关于在 Objective-C 中检查空字符串的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!