DenVog
DenVog

Reputation: 4286

String Passes Empty Test, Returns null

I am testing to see if a string is stored in NSUserDefaults. In theory, I thought the following was the answer:

if ( ![[[NSUserDefaults standardUserDefaults] authorName] isEqual: @""] )
{
  NSLog(@"The default must be set, the string is not equal to empty.");
  NSString *authorName = [[NSUserDefaults standardUserDefaults] authorName];
}

In practice, it always tested that something was there, but then returned a value of "(null)", when I try to use it. Can someone tell me why?

Ultimately, I think I've solved the problem with the following, but I'm not clear why the first test case did not work as I expected.

if ( [[[NSUserDefaults standardUserDefaults] authorName]  length] != 0 )

Thanks.

Upvotes: 0

Views: 173

Answers (1)

driis
driis

Reputation: 164331

The nil string is not equal to the empty string. That is why the first test passes but returns nil - because NSUserDefaults will return nil if no value is stored.

The reason why comparing length to zero works, is because when calling a method on a nil reference in objective-c, nil is returned. This is different from most other language, which would instead throw an exception in this case. Because length is NSInteger, nil becomes zero.

Comparing length to zero should be safe, but what you really is trying to test is whether a string is stored for the given key in the defaults. In that case, you can simply compare to nil:

if ([[NSUserDefaults standardUserDefaults] authorName] != nil)
{
    ....
}

Upvotes: 1

Related Questions