NSString is empty

2020-05-11 19:44发布

How do you test if an NSString is empty? or all whitespace or nil? with a single method call?

8条回答
何必那么认真
2楼-- · 2020-05-11 20:41

Should be easier:

if (![[string stringByReplacingOccurencesOfString:@" " withString:@""] length]) { NSLog(@"This string is empty"); }
查看更多
小情绪 Triste *
3楼-- · 2020-05-11 20:44

Based on the Jacob Relkin answer and Jonathan comment:

@implementation TextUtils

    + (BOOL)isEmpty:(NSString*) string {

        if([string length] == 0 || ![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
            return YES;
        }

        return NO;
    }

    @end
查看更多
登录 后发表回答