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


当前回答

只需将字符串传递给以下方法:

+(BOOL)isEmpty:(NSString *)str
{
    if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str  isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
        return YES;
    }
    return NO;
}

其他回答

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

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

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

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

快乐编码…

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

让我们假设你的字符串名字是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
}

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

你最好使用这个类别:

@implementation NSString (Empty)

    - (BOOL) isWhitespace{
        return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
    }

@end

我见过的最好的解决方案之一(比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);
}