我可以从其他班级观看NSNotification吗?

can*_*boy 6 iphone objective-c nsnotifications nsnotificationcenter ios

我正试着绕过NSNotificationCenter.如果我的App代表中有这样的内容:

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

-(void)something:(NSNotification *) notification
{
  // do something

}
Run Code Online (Sandbox Code Playgroud)

我可以在另一个视图控制器中看到这个吗?在我的情况下,我想在带有表的视图控制器中观察它,然后在收到通知时重新加载表.这可能吗?

Jon*_*asG 13

是的你可以这样做:

在A类:发布通知

 [[NSNotificationCenter defaultCenter] postNotficationName:@"DataUpdated "object:self];
Run Code Online (Sandbox Code Playgroud)

在B类中:首先注册通知,然后编写一个方法来处理它.您将相应的选择器提供给方法.

//view did load
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil];


-(void)handleUpdatedData:(NSNotification *)notification {
    NSLog(@"recieved");
}
Run Code Online (Sandbox Code Playgroud)


Osc*_*mez 4

是的,你可以,这就是 的全部目的NSNotification,你只需添加你想要作为观察者的视图控制器,就像你在应用程序委托上所做的那样,它就会收到通知。

您可以在这里找到更多信息:通知编程

  • @Cannyboy 是的,您可以根据需要向单个通知添加任意数量的观察者。 (2认同)