What is the best was to determine if an NSString is empty? Right now I am using the following:
if (string == nil || [string isEqualToString:@""]) {
// do something }
Thanks for any advice.
if ([string length] == 0) {
// do something
}
If the string is nil
, then the message to nil
will return zero, and all will still be well.
NSString
, something like isNotEmpty
, that you can do your custom checks in. Then you can just do if ([string isNotEmpty]) { … }
and it will also handle nil
s properly…NO
. Maybe hasValue
or something of that sort would be better.This will not only check if there is nothing in the string but will also return false if it is just whitespace.
NSString *tempString = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([tempString length] != 0) {
//There is something in the string.
} else {
//There is nothing or it is just whitespace.
}
-stringByReplacingOccurrencesOfString:withString:
is not especially efficient. Much better to test what you're actually looking for: non-whitespace characters. !myString || [myString rangeOfCharacterFromSet:[[NSCharacterSet whitespaceCharacterSet] invertedSet].location == NSNotFound
(In this case, you have to test whether myString
is nil
explicitly because an NSRange
resulting from messaging nil
won't have NSNotFound
in its location
field.)Not good solving
[nil length]
is 0
(0==0)
is 1
then ([string length] == 0)
will be 1
. Although it is wrong.
The best way is
if (![string length]) {
}