我正在使用我的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.
为什么启动应用两次才能使更改后的设置生效?
答案 0 :(得分:4)
NSUserDefaults会定期与磁盘同步(通常每隔30秒左右)。此同步过程允许它写出对磁盘的更改,但也可以获取在磁盘上所做的更改。尝试在[[NSUserDefaults standardUserDefaults] synchronize]
方法的最顶部调用-applicationDidBecomeActive:
。