[英]The NSNotificationCenter is never executed
這是我的代碼。
在這里創建名為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];
}
在我的第二個ViewController中。 點按一個按鈕即可執行此代碼:
[[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"}];
}
我相信你遇到的問題可能與你的第二個視圖控制器中你在object
參數中傳遞self.dictKeys
的事實有關。 如果要通過NSNotificationCenter
傳遞數據,則應使用userInfo
參數。
Darshan的例子以正確的方式做到了這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.