Mark S.
Mark S.

Reputation: 1546

How to determine if NSString is empty

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.

Upvotes: 9

Views: 8472

Answers (3)

user1212854
user1212854

Reputation:

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.
}

Upvotes: 2

Oleg
Oleg

Reputation: 568

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]) {

}

Upvotes: 0

John Calsbeek
John Calsbeek

Reputation: 36497

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.

Upvotes: 24

Related Questions