Popcorn
Popcorn

Reputation: 5348

objC checking empty string, isEqualToString:@"" vs length

I have a string

NSString hi;

and I don't know what values will get initialized to it. Could be nil, could be empty string, could be anything.

Are there any advantages to using

if (![hi length])

vs

if (![hi isEqualToString:@""])

It seems like both cases return the same values for empty string, nil, and any other type of string. I would guess length is better because it's more efficient. It just returns a variable, where as isEqualToString has to do a comparison.

Upvotes: 1

Views: 4571

Answers (3)

Chuck
Chuck

Reputation: 237020

They don't do the same thing.

[hi length] will return 0 for nil or an empty string and nonzero for any other string.

[hi isEqualToString:@""] will return 1 when hi is an empty string and 0 when hi is nil or any non-empty string.

In other words, the only value of hi for which the two lines of code give the same result is nil.

You probably wanted the behavior of option #1 (treating either nil or an empty string as "blank" and any other value as "not blank"), so that would be the one to use.

Upvotes: 7

user529758
user529758

Reputation:

Are there any advantages to using if (![hi length])

Yes. It can check for an empty string and for a nil at the same time. You can't do this with isEqualToString:, since if the string is nil, then any message sent to it will return zero, so it won't appear to be equal to the empty string, hence requiring another check.

By the way, for clarity, you should consider using if (hi.length != 0).

Upvotes: 4

user1822086
user1822086

Reputation:

I would do the following

if (hi && ![hi isEqualToString:@""]) {

}

![hi isEqualToString:@""] alone will get you a true if hi is nil.

Upvotes: 2

Related Questions