加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 用-applicationWillTerminate编写的NSUserDefaul

发布时间:2020-12-14 18:13:39 所属栏目:百科 来源:网络整理
导读:我已将下面的代码放在AppDelegate中,但是当我再次启动应用程序时,我注意到值仍然保存(Not NULL).这是为什么? 代码: - (void)applicationWillTerminate:(UIApplication *)application{ [[NSUserDefaults standardUserDefaults] setObject:NULL forKey:@"roo
我已将下面的代码放在AppDelegate中,但是当我再次启动应用程序时,我注意到值仍然保存(Not NULL).这是为什么?

代码:

- (void)applicationWillTerminate:(UIApplication *)application
{       [[NSUserDefaults standardUserDefaults]
         setObject:NULL forKey:@"roomCat"];
        [[NSUserDefaults standardUserDefaults]
         setObject:NULL forKey:@"TFA"];
        [[NSUserDefaults standardUserDefaults]
        setObject:NULL forKey:@"comments"];

}

谢谢.

解决方法

您应该使用-removeObjectForKey:而不是设置NULL.前者是消除价值的官方方式,而后者是无证行为.

在任何情况下,如果使用-removeObjectForKey:不起作用,那么您可以添加一个调用

[[NSUserDefaults standardUserDefaults] synchronize];

在末尾.但只有在没有它的情况下才能发挥作用.原因是因为调用-synchronize(相对)昂贵,所以只有在需要确保正确性时才应该这样做.

再看看之后,我怀疑你真正的问题是这个方法根本没有被调用.在iOS 4及更高版本中,当应用程序进入后台时,它们不会调用此方法,而是调用-applicationDidEnterBackground:.您应该尝试将此代码放在那里.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读