我可以观看另一个class的NSNotification吗?
我试图让我的头在NSNotificationCenter。 如果我在我的App Delegate中有这样的东西:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(something:) name:@"something" object:nil]; ----- -(void)something:(NSNotification *) notification { // do something }
我可以以某种方式在另一个视图控制器中看这个吗 在我的情况下,我想用一个表格在视图控制器中观看它,然后在收到通知时重新加载表格。 这可能吗?
是的,你可以这是NSNotification
的全部目的,你只需要添加你想要的观察控制器作为观察员完全一样的方式,你的应用程序委托,它会收到通知。
你可以在这里find更多的信息: 通知编程
是的,你可以这样做:
在Aclass:发布通知
[[NSNotificationCenter defaultCenter] postNotficationName:@"DataUpdated "object:self];
在B类中:首先注册通知,然后写一个方法来处理它。 你给相应的select器的方法。
//view did load [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil]; -(void)handleUpdatedData:(NSNotification *)notification { NSLog(@"recieved"); }
当然,这是可能的,这是通知的重点。 使用addObserver:selector:name:object:
是注册接收通知的方式(您应该在表视图控制器中执行此操作),并且可以使用postNotificationName:object:userInfo:
来发布任何类的通知。
阅读Notofication编程主题了解更多信息。
你可以注册观察通知在任何多的class级,只要你喜欢。 你只需要“冲洗和重复”。 包括代码注册为您的视图控制器中的观察员(也许在viewWillAppear :)然后重新加载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]; }
你应该只是添加一个Observer
并给出一个不同的selector
方法,如果你希望该viewController
行为有所不同,当通知发布。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingOtherThing:) name:@"something" object:nil]; -(void)somethingOtherThing:(NSNotification *) notification { // do something }