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


当前回答

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

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

其他回答

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

+(BOOL)isStringEmpty:(NSString *)str {
     if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
            return YES;
       }
      return NO;
  }

你可以检查你的字符串是空的或不是我使用这个方法:

+(BOOL) isEmptyString : (NSString *)string
{
    if([string length] == 0 || [string isKindOfClass:[NSNull class]] || 
       [string isEqualToString:@""]||[string  isEqualToString:NULL]  ||
       string == nil)
     {
        return YES;         //IF String Is An Empty String
     }
    return NO;
}

最佳实践是创建一个共享类UtilityClass并使用这个方法,这样你就可以通过在应用程序中调用它来使用这个方法。

//Different validations:
 NSString * inputStr = @"Hey ";

//Check length
[inputStr length]

//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr

//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
    BOOL isValid = NO;
    if(!([inputStr length]>0))
    {
        return isValid;

    }

    NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@".-"];
    [allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
    if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
    {
        // contains only decimal set and '-' and '.'

    }
    else
    {
        // invalid
        isValid = NO;

    }
    return isValid;
}

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

//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"];  
}

只需使用一个if else条件,如下所示:

方法1:

if ([yourString isEqualToString:@""]) {
        // yourString is empty.
    } else {
        // yourString has some text on it.
    }

方法2:

if ([yourString length] == 0) {
    // Empty yourString
} else {
    // yourString is not empty
}