gpt4 book ai didi

iphone - 为什么 iOS NSDefaults 需要启动两次才能生效?

转载 作者:行者123 更新时间:2023-12-03 20:47:08 33 4
gpt4 key购买 nike

我正在 iPhone 应用程序中使用 NSUserDefaults,由于某种原因,该应用程序需要启动/恢复两次才能使“设置”中的更改生效。相关代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

...

DLog(@"Registered default user defaults values.");
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DefaultUserDefaults" ofType:@"plist"]];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

...

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
DLog(@"rescheduling notifications...");
[self rescheduleAllNotifications];
}

- (void)rescheduleAllNotifications {
//
// Wipe the slate clean by cancelling all local notifications
//
[[UIApplication sharedApplication] cancelAllLocalNotifications];

//
// Only reschedule notifications if the user prefers to have them scheduled
//
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:@"notifications_enabled_preference"]) {
DLog(@"Notifications enabled. processing now...");

...

这是我的调试器输出(从 notifications_enabled_preference 设置为 YES 开始):

[Session started at 2011-01-31 14:25:58 -0600.]
AppDelegate application:didFinishLaunchingWithOptions:] Registered default user defaults values.
AppDelegate applicationDidBecomeActive:] rescheduling notifications...
AppDelegate rescheduleAllNotifications] Notifications enabled. processing now...

-> Switch to Settings and turn notifications_enabled_preference to NO, then re-launch the app

AppDelegate applicationDidBecomeActive:] rescheduling notifications...
AppDelegate rescheduleAllNotifications] Notifications enabled. processing now...


-> Click home screen button, then re-launch the app **again**

AppDelegate applicationDidBecomeActive:] rescheduling notifications...
AppDelegate rescheduleAllNotifications] Notifications disabled. Skipping notification processing.

为什么需要启动应用两次才能使更改的设置生效?

最佳答案

NSUserDefaults 定期将自身同步到磁盘(通常每 30 秒左右)。此同步过程可以将更改写入磁盘,但也可以拾取在磁盘上所做的更改。尝试在 -applicationDidBecomeActive: 方法的最顶部调用 [[NSUserDefaults standardUserDefaults]一线同步]

关于iphone - 为什么 iOS NSDefaults 需要启动两次才能生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4855760/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com