-2

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

// 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?

编辑

I'm trying to save a new value when the value does not exists in the selector, however it always appear to return null in the selector after the app is restarted.

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

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

1 回答 1

0

简短的回答是,在调用和返回时,显然您没有将任何对象存储到standardUserDefaultsfor 键中。@"myKey"-handleNotifications:[[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]nil

SomeNotification您是否在处理除in之外的其他通知-handleNotifications:?如果是这样,您可能会在行-handleNotifications:前输入

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

执行。

于 2012-12-29T19:18:22.227 回答