Objective-c – How to properly work (retrieve values) with NSUserDefaults

cocoacocoa-touchiphoneobjective-c

I have a simple method in my code which looks like the following:

- (BOOL)isFirstTimeLogin 
{
    NSString *t_gName = 
    [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:kGroupIdentifierKey]];
    if ([t_gName isEqualToString:@""] || t_gName == nil) {
        DLog(@"LoginViewController, m:::isFirstTimeLogin, First time login happening.");
        return YES;
    }

    DLog(@"LoginViewController, m:::isFirstTimeLogin, Not a first time login.");
    return NO;
}

Simply what this does is go to the Settings bundle, and retrieve a value from a PSTextFieldSpecifier. If I manually go in and add some arbitrary text, the code works as expected. However, whenever I first install the app on a new device, the first condition is executing as false, which it should be true. After stepping through the code, gdb proves that the object is indeed nil as well:

(gdb) po t_gName
(null)

What am I possibly doing wrong here? Why is it the condition is failing for the first time the app is installed and t_gName is an empty/null PSTextFieldSpecifier. I even went as far as trying to add a DefaultValue in my Settings bundle of an empty string.

Best Solution

[NSString stringWithFormat:@"%@", nil];

This creates something like this:

@"(null)"

and is therefore neither nil nor equal to @"".

by the way

  1. You don't need stringWithFormat: at all.
  2. Don't check for string == nil but for !string
  3. You don't have to check for an empty string, as there is one set or it's nil.
  4. Use a better name than t_gName, there's no reason for short names.

Like this:

- (BOOL)isFirstTimeLogin 
{
    NSString *groupIdentifier = [[NSUserDefaults standardUserDefaults]
                                    objectForKey:kGroupIdentifierKey];
    if (!groupIdentifier) {
        DLog(@"First time login.");
        return YES;
    }

    DLog(@"Not a first time login.");
    return NO;
}
Related Question