第一个 NSLog 可以很好地显示字典的内容。第二个日志引发以下异常...
该程序试图欺骗您,它看起来就像是您的字典,因为您的字典在通知中。从异常中您可以看到您的对象实际上来自一个名为 NSConcreteNotification 的类。
这是因为通知方法的参数始终是 NSNotification 对象。这将起作用:
- (void)hotSpotMore:(NSNotification *)notification {
NSLog(@"%@", notification.object);
NSLog(@"%@", [notification.object objectForKey:@"HelpTopic"]);
}
只是作为一个提示:对象通常是发送通知的对象,您应该将您的 NSDictionary 作为 userInfo 发送。
如果您这样做,我认为它会改进您的代码:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"HotSpotTouched" object:self userInfo:itemDetails];
- (void)hotSpotMore:(NSNotification *)notification {
NSLog(@"%@", notification.userInfo);
NSLog(@"%@", [notification.userInfo objectForKey:@"HelpTopic"]);
}
object 参数用于区分可以发送通知的不同对象。
假设您有两个不同的 HotSpot 对象,它们都可以发送通知。当您设置objectin时,addObserver:selector:name:object:您可以为每个对象添加不同的观察者。使用 nil 作为对象参数意味着应该接收所有通知,而不管发送通知的对象是什么。
例如:
FancyHotSpot *hotSpotA;
FancyHotSpot *hotSpotB;
// notifications from hotSpotA should call hotSpotATouched:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hotSpotATouched:) name:@"HotSpotTouched"
object:hotSpotA]; // only notifications from hotSpotA will be received
// notifications from hotSpotB should call hotSpotBTouched:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hotSpotBTouched:) name:@"HotSpotTouched"
object:hotSpotB]; // only notifications from hotSpotB will be received
// notifications from all objects should call anyHotSpotTouched:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(anyHotSpotTouched:) name:@"HotSpotTouched"
object:nil]; // nil == “any object”, so all notifications with the name “HotSpotTouched” will be received
- (void)hotSpotATouched:(NSNotification *)n {
// only gets notification of hot spot A
}
- (void)hotSpotBTouched:(NSNotification *)n {
// only gets notification of hot spot B
}
- (void)anyHotSpotTouched:(NSNotification *)n {
// catches all notifications
}