0

What is the correct way to check the contents of standardUserDefaults ?

If I print out what is stored in a key i get:

NSLog(@"logged_in_status : %@", [standardUserDefaults stringForKey:@"logged_in_status"]);
Output: logged_in_status : (null)

So it seems to be NSNull.

So I will add a check for that as follows:

 if ([[standardUserDefaults objectForKey:@"logged_in_status"] isKindOfClass:[NSNull class]])
        {
            NSLog(@"YES");
        }
        else
        {
            NSLog(@"NO");
        }

Output: NO

Why does this not resolve to the YES? Isn't it an NSNull?

I've been looking at this for a long time and can't see where the error is. Could anybody kindly explain where I've gone wrong on this?

Thanks, Code

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • 1
    the check is `[standardUserDefaults objectForKey:@"logged_in_status"] == nil` as nil is a special value – Francescu Nov 30 '14 at 17:23

2 Answers2

2

When you do the key lookup initially, you're not getting back an instance of NSNull, but instead no result at all: in other words, nil, which isn't the same thing as NSNull. That typically means that no value has been set for that key in the user defaults yet. (You can see this if you look at it under the debugger while stepping through-- the "stringified" version of nil happens to be "(null)" when you print it to the log, which is partly what I think may be confusing here.)

(If this distinction is fuzzy for you, have a look at the answer to this question about the differences between the various forms of "null" you might encounter: What are the differences between nil, NULL and [NSNULL nil]?)

As @Francescu suggests in a comment, if you're trying to do a check for "has this value ever been set", it could look something like:

NSString * loggedInStatus = [standardUserDefaults stringForKey:@"logged_in_status"];
if (!loggedInStatus) {
    NSLog(@"status not set");
} else {
    NSLog(@"status: %@", loggedInStatus);
}
Community
  • 1
  • 1
Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
0

Just some additional info to the other answers: when you format a string including the %@ format specifier, a nil value will format as "(null)" with parentheses. An instance of NSNullthe instance, since it's a singleton — formats as "<null>" with angle brackets.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154