NSString is empty

前端 未结 8 1850
伪装坚强ぢ
伪装坚强ぢ 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 05:51

    I use,

    + (BOOL ) stringIsEmpty:(NSString *) aString {
    
        if ((NSNull *) aString == [NSNull null]) {
            return YES;
        }
    
        if (aString == nil) {
            return YES;
        } else if ([aString length] == 0) {
            return YES;
        } else {
            aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if ([aString length] == 0) {
                return YES;
            }
        }
    
        return NO;  
    }
    
    + (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
    
        if ((NSNull *) aString == [NSNull null]) {
            return YES;
        }
    
        if (aString == nil) {
            return YES;
        } else if ([aString length] == 0) {
            return YES;
        } 
    
        if (cleanWhileSpace) {
            aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if ([aString length] == 0) {
                return YES;
            }
        }
    
        return NO;  
    }
    

提交回复
热议问题