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


当前回答

它就像if([myString isEqual:@""])或if([myString isEqualToString:@""])一样简单。

其他回答

基于多个答案,我创建了一个可以使用的类别,结合@iDevAmit和@user238824答案。

具体来说,它是按照以下顺序进行的

检查null/nil 检查if字符串是否为空使用它的长度计数。 检查字符串是否为空白。

//
//  NSString+Empty.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Empty)
- (BOOL)isEmptyOrWhiteSpacesOrNil;
@end

NS_ASSUME_NONNULL_END

实现

//
//  NSString+Empty.m

#import "NSString+Empty.h"

@implementation NSString (Empty)

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

- (BOOL)isEmptyOrWhiteSpacesOrNil {
     if(self == nil || [self isKindOfClass:[NSNull class]] || self.length==0 || [self isWhitespace] == YES) {
            return YES;
       }
      return NO;
  }

@end

/*
 Credits
 1. https://stackoverflow.com/a/24506942/7551807
 2. https://stackoverflow.com/a/1963273/7551807
 */

用法: 当然,如果字符串为空,函数将永远不会被触发。第一种情况是为了增加安全保障。我建议在尝试使用此方法之前检查可空性。

if (myString) {
  if [myString isEmptyOrWhiteSpacesOrNil] {
     // String is empty
  }
} else {
// String is null
}
//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;
}

马克的回答是正确的。但我想借此机会引用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);
}
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    

你最好使用这个类别:

@implementation NSString (Empty)

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

@end