views:

93

answers:

1
+1  Q: 

NSString is empty

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

+10  A: 

You can try something like this:

- (BOOL) isEmptyString:(NSString *) string {
    if([string length] == 0) { //string is empty or nil
        return YES;
    } else if([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
      //string is all whitespace
        return YES;
    }
    return NO;
 }

Check out the NSString reference on ADC.

Jacob Relkin
how can i do all that with a single method call?
Yazzmi
@Yazzmi, I edited my answer.
Jacob Relkin
Since he just wrote a function for you, call that. Although I would change it to return YES if it were empty, nil, or had whitespace - and NO if the string had any characters in it (the function as written will return NO if there are characters in the string).
Kendall Helmstetter Gelner
@Kendall, you can edit this you know ;)
Jacob Relkin
Yeah `stringCheck` isn't very descriptive; something like `isEmptyString` in a category on `NSString` would be better. ;)
Wevah