How to properly work (retrieve values) with NSUserDefaults
-
03-07-2019 - |
Question
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.
Solution
[NSString stringWithFormat:@"%@", nil];
This creates something like this:
@"(null)"
and is therefore neither nil
nor equal to @""
.
by the way
- You don't need
stringWithFormat:
at all. - Don't check for
string == nil
but for!string
- You don't have to check for an empty string, as there is one set or it's
nil
. - 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;
}
OTHER TIPS
Try this:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedFirstTime"])
{
// app already launched
NSLog(@"app already launched");
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedFirstTime"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"First Time");
// This is the first launch ever
}
}