如何正确工作(检索值)与NSUserDefaults [英] How to properly work (retrieve values) with NSUserDefaults

查看:126
本文介绍了如何正确工作(检索值)与NSUserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中有一个简单的方法,如下所示:

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;
}

这样做只需转到设置包,一个PSTextFieldSpecifier。如果我手动进入和添加一些任意文本,代码工作正常。但是,每当我第一次在新设备上安装应用程序时,第一个条件是执行为false,这应该是真的。在遍历代码后,gdb证明对象确实是nil:

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)

(gdb) po t_gName
(null)

我可能在这里做错了什么?为什么它的条件是第一次安装应用程序失败,t_gName是一个空/ null PSTextFieldSpecifier。我甚至去尝试在一个空字符串的设置包中添加一个DefaultValue。

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.

推荐答案

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

这会创建如下:

@"(null)"

c $ c> nil 也不等于 @

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


  1. 您不需要 stringWithFormat:

  2. 不要检查 string == nil ,但!string

  3. 您不必检查一个空字符串,因为有一个或 nil

  4. 使用比 t_gName 更好的名称,没有理由缩短名称。

  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.

像这样:

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

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

这篇关于如何正确工作(检索值)与NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆