如何知道是否存在 NSUserDefault?

发布于 2024-11-05 05:06:17 字数 669 浏览 2 评论 0原文

我用什么条件才能知道我使用的 NSUserDefaults ?

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

这就是我获取数据的方式。如果前缀 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}

但事实上,它不起作用。

谢谢你帮我!!

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 !!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌无敌 2024-11-12 05:06:17

我想进入if条件if
前缀 stringForKey:@"opening"
已经存在......

但是您正在使用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 )
}

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 )
}
韶华倾负 2024-11-12 05:06:17

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文