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.
[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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With