NSString is empty

前端 未结 8 1861
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 05:45

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

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 06:06

    This is what I use, an Extension to NSString:

    + (BOOL)isEmptyString:(NSString *)string;
    // Returns YES if the string is nil or equal to @""
    {
        // Note that [string length] == 0 can be false when [string isEqualToString:@""] is true, because these are Unicode strings.
    
        if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
            return YES;
        }
        string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
        if ([string isEqualToString:@""]) {
            return YES;
        }
    
        return NO;  
    }
    

提交回复
热议问题