怎么知道是否有NSUserDefault?

时间:2011-05-06 13:15:33

标签: iphone comparison nsstring nsuserdefaults

我使用什么条件来了解我使用的NSUserDefaults?

NSUserDefaults *preftest;
preftest=[NSUserDefaults standardUserDefaults];
NSString *opening = [preftest stringForKey:@"opening"];

这是我获取数据的方式。如果preftext stringForKey:@“opening”尚不存在,我想进入if条件......所以我试过了:

if (opening == nil) {
    ...
    NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
    [pref setObject:@"OK" forKey:@"pass"];
    NSString *finalfr = [pref stringForKey:@"opening"];
    NSLog(@"(here's the new value of opening: %@ )", finalfr);
    ...
}

if (opening != nil) {
    NSLog(@" != nil");
    // http request}

但是,它不起作用。

感谢帮助我!!

2 个答案:

答案 0 :(得分:1)

也许不是将指针与nil进行比较,而是可以将内容与空字符串[opening isEqualToString:@“”]进行比较,后者返回一个布尔值。

答案 1 :(得分:1)

  

我想进入if条件if   preftext stringForKey:@“开放”   已经存在....

但您正在测试opening != nil是否存在。 如果您想测试它是否不存在,那么它将是opening == nil!opening

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *opening = [prefs stringForKey:@"opening"];

if (!opening) {
    [prefs setObject:@"OK" forKey:@"opening"];
    opening = [prefs stringForKey:@"opening"];
    NSLog(@"(here's the new value of opening: %@ )", opening);
    // prints: (here's the new value of opening: OK )
}