Iphone 我可以看另一节课的通知吗?
我正试着在国家信息中心转转。如果我的应用程序代理中有类似的内容:Iphone 我可以看另一节课的通知吗?,iphone,objective-c,ios,nsnotifications,nsnotificationcenter,Iphone,Objective C,Ios,Nsnotifications,Nsnotificationcenter,我正试着在国家信息中心转转。如果我的应用程序代理中有类似的内容: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(something:) name:@"something"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(something:)
name:@"something"
object:nil];
-----
-(void)something:(NSNotification *) notification
{
// do something
}
我可以在另一个视图控制器中观看吗?在我的例子中,我希望在带有表的视图控制器中查看它,然后在收到通知时重新加载表。这可能吗?是的,你可以。这就是
NSNotification
的全部目的,你只需添加你想要作为观察者的视图控制器,就像你在应用程序代理上所做的那样,它就会收到通知
您可以在这里找到更多信息:当然有可能,这就是通知的全部要点。使用
addObserver:selector:name:object:
是注册接收通知的方式(您应该在表视图控制器中执行此操作),并且可以使用postNotificationName:object:userInfo:
发布来自任何类的通知
阅读了解更多信息。是的,您可以这样做: A类:发布通知
[[NSNotificationCenter defaultCenter] postNotficationName:@"DataUpdated "object:self];
在类B中:首先注册通知,然后编写一个方法来处理它。
将相应的选择器指定给该方法
//view did load
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil];
-(void)handleUpdatedData:(NSNotification *)notification {
NSLog(@"recieved");
}
如果希望
viewController
在发布通知时表现不同,您应该将其添加为一个观察者
,并提供一个不同的选择器
方法
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(somethingOtherThing:)
name:@"something"
object:nil];
-(void)somethingOtherThing:(NSNotification *) notification
{
// do something
}
您可以注册以观察任意多个类中的通知。你只需要“冲洗并重复”。在视图控制器中包含注册为观察者的代码(可能在ViewWillDisplay:)然后从方法重新加载tableView:
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(something:) name:@"something" object:nil];
}
-(void)something:(NSNotification *) notification
{
[self.tableView reloadData];
}
当不再需要通知时,最好注销视图控制器:
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@Cannyboy是的,您可以在一个通知中添加任意多的观察者。然后,我在哪里删除观察者?