Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString Comparison Where @"" == nil

I want to compare two strings where I want nil to be equal to a blank string (@""). Right now I'm doing this, which works fine:

if ([self.firstName ? self.firstName : @"" isEqualToString:anotherContact.firstName ? anotherContact.firstName : @""]) {
    // They are equal.
}

But there seems like there might be something simpler that I'm missing.

I'm not looking for case sensitivity here. If case is different then the test should fail.

like image 834
Dave Batton Avatar asked May 28 '14 23:05

Dave Batton


2 Answers

[string length]

works, but it will return zero if it is nil also. If that's acceptable to you, it's simpler.

btw nested ternary operators are OK in the privacy of your own home, but if you're writing code to share maybe it's better to spread it out a bit so it's obvious.

In response to comments, the way I would do it is like this:

    if((([a length] == 0) && ([b length] == 0)) ||
        ([a isEqualToString:b])) {
        // they are equal
    }

If either clause succeds then the strings are equal. The second catches any non-nil strings that are actually equal, including @"" == @"". The first catches a and b both nil, or one nil and one @"". I did write the first as ((a == nil) && (b == nil)) at first but you said @"" should equal nil.

like image 69
Adam Eberbach Avatar answered Sep 17 '22 17:09

Adam Eberbach


you can use ?: operator. a ? a : b is same as a ?: b (with side effect of a performed once only)

if ([self.firstName ?: @"" isEqualToString:anotherContact.firstName ?: @""]) {
    // They are equal.
}
like image 21
Bryan Chen Avatar answered Sep 21 '22 17:09

Bryan Chen