如何正确工作(检索值)与NSUserDefaults [英] How to properly work (retrieve values) with 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 @""
.
- 您不需要
stringWithFormat:
。 - 不要检查
string == nil
,但!string
- 您不必检查一个空字符串,因为有一个或
nil
。 - 使用比
t_gName
更好的名称,没有理由缩短名称。
- 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.
像这样:
- (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屋!