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


当前回答

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

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

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

快乐编码…

其他回答

可能这个答案是已经给出的答案的副本,但我在检查条件的顺序上做了一些修改和更改。请参考以下代码:

+(BOOL)isStringEmpty:(NSString *)str {
     if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
            return YES;
       }
      return NO;
  }
if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

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

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

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

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

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

现在你可以使用:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

你可以很容易地检查字符串是否为空:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}
- (BOOL)isEmpty:(NSString *)string{
    if ((NSNull *) string == [NSNull null]) {
        return YES;
    }
    if (string == nil) {
        return YES;
    }
    if ([string length] == 0) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        return YES;
    }
    if([[string stringByStrippingWhitespace] isEqualToString:@""]){
        return YES;
    }
    return NO;
}