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
2010-08-08 21:45:52
how can i do all that with a single method call?
Yazzmi
2010-08-08 21:48:41
@Yazzmi, I edited my answer.
Jacob Relkin
2010-08-08 21:58:43
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
2010-08-08 21:59:10
@Kendall, you can edit this you know ;)
Jacob Relkin
2010-08-08 22:06:48
Yeah `stringCheck` isn't very descriptive; something like `isEmptyString` in a category on `NSString` would be better. ;)
Wevah
2010-08-08 23:25:36