在Objective-C中检查空字符串的正确方法是什么? [英] What is the right way to check for a null string in Objective-C?

查看:99
本文介绍了在Objective-C中检查空字符串的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的iPhone应用程式中使用这个程式。

  if(title == nil){
// do
}

但它抛出一些异常,控制台显示标题是 (null)。



所以我现在使用这个:

  if(title == nil || [title isKindOfClass:[NSNull class]]){
// do something
}

有什么区别,什么是确定字符串是否为空的最好方法?

解决方案

正如其他人已经指出的,在Cocoa / Objective C下有许多种类的null。但是还要注意的是[title isKindOfClass:[NSNull class]]是无意义的,因为[NSNull null]被记录为一个单例,所以你可以只检查指针相等。请参见可可主题:使用空。 p>

所以一个很好的测试可能是:

  if id)[NSNull null] || title.length == 0)title = @Something;注意如何使用这样一个事实,即使title是nil,title.length将返回0/0。 nil / false,即在这种情况下为0,所以你不必有特殊情况。这是新的Objective C的人有麻烦习惯,特别是来自其他语言的消息/方法调用nil崩溃。


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?

解决方案

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";

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆