如何在Objective-C中测试NSString是否为空?


当前回答

非常有用的帖子,添加NSDictionary支持以及一个小的变化

static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && ![thing respondsToSelector:@selector(count)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [thing count] == 0);
}

其他回答

空字符串有两种方式:

1) @"" //不包含空格

2) @" " //包含空格

严格来说,这两个字符串都是空的。我们可以用条件一来写出这两个式子

if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
    NSLog(@"Empty String");
}
else
{
    NSLog(@"String contains some value");
}

你有两个方法来检查字符串是否为空:

让我们假设你的字符串名字是NSString *strIsEmpty。

方法1:

if(strIsEmpty.length==0)
{
    //String is empty
}

else
{
    //String is not empty
}

方法2:

if([strIsEmpty isEqualToString:@""])
{
    //String is empty
}

else
{
    //String is not empty
}

选择上述任何一种方法,了解字符串是否为空。

你可以检查[string length] == 0。这将检查它是否是一个有效的空字符串(@"")以及它是否为nil,因为在nil上调用length也将返回0。

它就像if([myString isEqual:@""])或if([myString isEqualToString:@""])一样简单。

马克的回答是正确的。但我想借此机会引用Wil Shipley在他的博客上分享的一般化的isEmpty:

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);
}