2015-04-22 25 views
0

從不調用NSNotificationCenter選擇器方法。NSNotificationCenter中出現問題

PostNotification是遵循:

- (IBAction)go:(id)sender { 
AnotherViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"AnotherViewController"]; 

[[NSNotificationCenter defaultCenter] 
postNotificationName:@"TestNotification" 
object:self]; 




[self.navigationController pushViewController:obj animated:YES]; 

} 

在AnotherViewController.m遵守通知:

- (void)viewDidLoad { 
[super viewDidLoad]; 

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(receiveTestNotification:) 
              name:@"TestNotification" 
              object:nil]; 


// Do any additional setup after loading the view. 
    } 

和receiveTestNotification是:

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


if ([[notification name] isEqualToString:@"TestNotification"]) 
    NSLog (@"Successfully received the test notification!"); 
} 

問題是什麼?謝謝

+0

那段代碼對我來說很合適。 – trojanfoe

+0

但不適用於我。控制永遠不會到達選擇器方法。 –

回答

0

您應該將添加觀察者方法移動到視圖控制器的初始化。因爲您在AnotherViewController註冊自己以接收通知之前發佈通知。

- (instancetype)initWithCoder:(NSCoder *)aDecoder 
    { 
     self = [super initWithCoder:aDecoder]; 
     if (self) { 
      [[NSNotificationCenter defaultCenter] addObserver:self 
                selector:@selector(receiveTestNotification:) 
                 name:@"TestNotification" 
                 object:nil]; 
     } 
     return self; 
    } 
+0

它的工作。謝謝cekisakurek :) –

+0

歡迎您:)。如果你接受答案爲解決方案,那將是非常好的。 – cekisakurek

+0

iam新的在stackoverflow,不知道如何接受作爲答案..告訴我的過程 –