NSUserDefaults在NSNotificationCenter选择器中返回null

时间:2012-12-29 17:48:29

标签: ios nsuserdefaults nsnotificationcenter

我有以下代码来注册观察者:

// This logs some value
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]); 
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleNotifications:)
                                             name:SomeNotification
                                           object:nil];

- (void) handleNotifications: (NSNotification *)notification
{
  // This logs null
  NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]); 
}

为什么myKey在通知选择器中返回null?

修改

我正在尝试在选择器中不存在值时保存新值,但是在应用程序重新启动后,它总是在选择器中返回null。

- (void) handleNotifications: (NSNotification *)notification
{

  if (![[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"])) {
    NSLog(@"Saving");
    [[NSUserDefaults standardUserDefaults] setObject: @"ABC", forKey:@"myKey"]
    [[NSUserDefaults standardUserDefaults] synchronize];
  }
}

1 个答案:

答案 0 :(得分:0)

简短的回答是,在调用standardUserDefaults并且@"myKey"返回{-handleNotifications:时,显然您没有将任何对象存储到密钥[[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]的{​​{1}}中{1}}。

您是否正在处理nilSomeNotification以外的其他通知?如果是这样,您可能会在行

之前输入-handleNotifications:
-handleNotifications:

执行。

相关问题