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


当前回答

另一个选项是用isEqualToString检查它是否等于@"":如下所示:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

其他回答

我检查了一个空字符串使用以下代码:

//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0 
       || strMyString.text isEqual:@"")) {

   [AlertView showAlert:@"Please enter a valid string"];  
}

空字符串有两种方式:

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

2) @" " //包含空格

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

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

马克的回答是正确的。但我想借此机会引用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);
}

第一种方法是有效的,但如果字符串中有空格(@" ")则无效。所以在测试之前必须清除这些空白。

这段代码清除了字符串两边的所有空格:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

一个好主意是创建一个宏,这样你就不必输入这一行怪物:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

现在你可以使用:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");
if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}