开发者

How know if there is a NSUserDefault?

What condition do I use to know it the NSUserDefaults I use?

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

This is the way I'm getting the datas. I want to get into the if condition if the preftext stringForKey:@"opening" doesn't already exist.... So I tried :

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}

But inded, it doesn't work.

Thanks to help me !!


I want to get into the if condition if the preftext stringForKey:@"opening" doesn't already exist....

But you are testing if it does exist with opening != nil. If you want to test if it does NOT exist, it would be opening == nil or just !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 )
}


Maybe instead of comparing the pointer against nil, you could compare the contents against an empty string [opening isEqualToString: @""], which returns a boolean.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜