我有以下代码来注册观察者:
// 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];
}
}
答案 0 :(得分:0)
简短的回答是,在调用standardUserDefaults
并且@"myKey"
返回{-handleNotifications:
时,显然您没有将任何对象存储到密钥[[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]
的{{1}}中{1}}。
您是否正在处理nil
中SomeNotification
以外的其他通知?如果是这样,您可能会在行
-handleNotifications:
-handleNotifications:
执行。