如何在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);
}

其他回答

非常有用的帖子,添加NSDictionary支持以及一个小的变化

static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && ![thing respondsToSelector:@selector(count)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [thing count] == 0);
}

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

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}

基于多个答案,我创建了一个可以使用的类别,结合@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
}

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

+(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并使用这个方法,这样你就可以通过在应用程序中调用它来使用这个方法。

看看这个:

if ([yourString isEqualToString:@""])
{
    NsLog(@"Blank String");
}

Or

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}

希望这能有所帮助。