NSString Comparison Where @ "" == nil

I want to compare two lines where I want nil to be equal to an empty line (@ ""). Now I am doing this, which works great:

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

But it looks like there might be something simpler that I am missing.

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

+8
ios objective-c cocoa-touch
source share
5 answers
 [string length] 

works, but it will return zero if it is also zero. If this is acceptable to you, it is easier.

btw nested ternary operators are fine in your own home, but if you are writing code for sharing, it might be better to decompose it so that it is obvious.

In response to the comments, how would I do this:

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

If one sentence is executed, the lines are equal. The second catches any non-zero lines that are actually equal, including @"" == @"" . The first catches a and b both nil and one nil and one @"" . At first I wrote first as ((a == nil) && (b == nil)) , but you said that @"" should be zero.

+13
source share

can you use the ?: operator. a ? a : b a ? a : b same as a ?: b (with a side effect a only occurs once)

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

I would suggest a function in this case:

 NSString * emptyStringIfNil(NSString * s) { if( !s ) return @""; else return s; } 

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

Much easier to read. You can do internal functions as you wish; I would say that a ternary conditional mind would be reasonable there.

+9
source share
 - (NSString*)firstName { return _firstName ? _firstName : @""; } 

One of several important reasons for using getter / setter methods of properties is that it allows you to apply certain conditions to a property, for example, never be nil.

You can easily make sure that properties such as firstName are never executed by implementing the special getter or setter method in one place, and then you don’t need to worry about weird triple operators every time you access these properties.

+2
source share

Why not make it a macro? This seems to be the perfect use case.

Alternatively, you can add a category to NSString: +string:isEqualToString:

+2
source share

All Articles