views:

218

answers:

2

hi all,

I got the problem that the if-statement doesn't work. After the first code line the variable contains the value "(null)", because the user who picked the contact from his iphone address book doesn't set the country key for this contact, so far so good.

but if I check the variable, it won't be true, but the value is certainly "(null)"... does someone have an idea?

 NSString *country = [NSString [the dict objectForKey:(NSString *)kABPersonAddressCountryKey]];

 if(country == @"(null)")
 {
      country = @"";
 }

thanks in advance
sean

+4  A: 

The correct expression would be:

if (country == nil)

which can be further shortened to:

if (!country)

And if you really want to test equality with the @"(null)" string, you should use the isEqual: method or isEqualToString:

if ([country isEqualToString:@"(null)"])

When you compare using the == operator, you are comparing object addresses, not their contents:

NSString *foo1 = [NSString stringWithString:@"foo"];
NSString *foo2 = [NSString stringWithString:@"foo"];
NSAssert(foo1 != foo2, @"The addresses are different.");
NSAssert([foo1 isEqual:foo2], @"But the contents are same.");
NSAssert([foo1 isEqualToString:foo2], @"True again, faster than isEqual:.");
zoul
I already tried that, it doesn't work with nil. because if I would set this variable to a text field, the text field would show "null" and wouldn't be empty like you might expect
Sean
thanks zoul, with isEqualToString it works. i've never made a difference between ==, isEqualToString or compare... what is exactly the difference between these comparing methods?
Sean
oh ok, thanks a lot for this short explanation.
Sean
In your example, the expression @"foo" becomes an internalised string, and therefore all other references to the same in this fashion will point to the same object. It's an optimisation. Therefore, @"foo" == @"foo" is true.
Jasarien
Yes, I know, that’s why I said *probably* different (I wanted to keep things simple). I rewrote the example using `stringWithString:`, hope there’s no magic involved there. Thank you.
zoul
A: 

That was a great answer I didn't know there was all those different ways of checking for nil or null string.

vladzz