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


当前回答

我见过的最好的解决方案之一(比Matt G的更好)是这个改进的内联函数,我从一些Git Hub repo (Wil Shipley的一个,但我找不到链接):

// Check if the "thing" passed is empty
static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([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)];
}

试试下面的方法

NSString *stringToCheck = @"";

if ([stringToCheck isEqualToString:@""])
{
   NSLog(@"String Empty");
}
else
{
   NSLog(@"String Not Empty");
}

简单地检查你的字符串长度

 if (!yourString.length)
 {
   //your code  
 }

发送给NIL的消息将返回NIL或0,因此不需要测试NIL:)。

快乐编码…

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