我有以下代码:
NSString *content = [[NSUserDefaults standardUserDefaults] stringForKey:@"mykey"];
NSLog(@"string is %@",content);
if ([content stringIsEmpty]){
NSLog(@"empty string");
}else{
NSLog(@"string is not empty");
}
stringIsEmpty是NSString
上的类别类别:
- (BOOL ) stringIsEmpty {
if ((NSNull *) self == [NSNull null]) {
return YES;
}
if (self == nil) {
return YES;
} else if ([self length] == 0) {
return YES;
}
return NO;
}
输出结果为:
string is (null)
string is not empty
它怎么可能是null而不是同时为空?
答案 0 :(得分:3)
会发生什么:
[content stringIsEmpty:YES]
NO
为content
时,将返回false(nil
)。所以你的代码将采用
NSLog(@"string is not empty");
分支。这会更好:
if (content && [content stringIsEmpty:YES]){
...
更好的方法是颠倒方法的语义:
if ([content stringIsNotEmpty]) {
这样可以正常使用,因为当content
为nil
时它将返回NO
,当它不是nil
时,它会执行您的方法。
编辑:
在Objective-C中,向nil
发送邮件是合法的,根据定义,评估为nil
。谷歌的“客观c发送消息为零”。
在另一种语言(C ++)中,您的代码会崩溃(实际上是未定义的行为,但为了简单起见)。
答案 1 :(得分:1)
我使用一个小函数来测试空虚。它的工作原理不仅仅是字符串:
static inline BOOL isEmpty(id thing) {
return thing == nil
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
我通常会在我的pch文件中导入它 - 您可以看到它以及归因:https://gist.github.com/325926
正如@sergio已经指出的那样 - 当你的字符串是nil
时,你不能发送它为nil-ness测试它的消息 - 因为向nil发送消息对void方法没有任何作用,并返回nil方法返回的地方。
同时强>
您使用参数
调用方法if ([content stringIsEmpty:YES])
但是您的方法声明不需要一个:
- (BOOL ) stringIsEmpty {
那是什么意思?
答案 2 :(得分:0)
您必须检查方法之外的'content == nil'案例。
如果您希望只能调用一个方法,请将方法更改为测试为肯定的方法,例如“stringHasContent”,如果YES
则返回self.length > 0
。