这是我的代码。
在这里创建名为Example
的Notification观察者到ViewController中
- (void)addObserverExample
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(example:)
name:@"Example"
object:nil];
}
- (void)example:(NSNotification *)notification{
NSLog(@"Example!!!");
}
来自viewDidLoad
注册我的观察员
- (void)viewDidLoad
{
[self addObserverExample];
}
在我的第二个View Controller中。点击按钮时执行以下代码:
[[NSNotificationCenter defaultCenter] postNotificationName:@"Example" object:self.dictKeys userInfo:nil];
我遇到的问题是通知永远不会执行。
任何的想法。
根据您的问题为NSNotificationCenter创建了演示,它对我来说很好。这是代码的链接:NSNotificationCenter Demo
- (void)viewDidLoad {
[super viewDidLoad];
[self addObserverExample];
}
- (void)addObserverExample
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(example:)
name:@"Example"
object:nil];
}
- (void)example:(NSNotification *)notification{
NSLog(@"Example!!!");
NSLog(@"%@",notification.userInfo);
}
- (IBAction)btnFireNotification:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"Example" object:nil userInfo:@{@"key" : @"value"}];
}
我相信你遇到的问题可能与你的第二个视图控制器中你在self.dictKeys
参数中传递object
这一事实有关。如果要通过NSNotificationCenter
传递数据,则应使用userInfo
参数。
Darshan的例子以正确的方式做到了这一点。