Can I see NSNotification from another class?

I am trying to get around the NSNotificationCenter. If I have something like this in my App Delegate app:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(something:) name:@"something" object:nil]; ----- -(void)something:(NSNotification *) notification { // do something } 

Is there any way to see this in another controller? In my case, I would like to see it in the view controller with a table, and then reload the table when I receive a notification. Is it possible?

+6
source share
5 answers

Yes, it could be the whole purpose of NSNotification , you just need to add the view controller that you want as an observer, just like in your applicationโ€™s deletion, and it will receive a notification.

You can find more information here: Programming notifications

+4
source

Yes, you can do it like this:

In class A: post a notice

  [[NSNotificationCenter defaultCenter] postNotficationName:@"DataUpdated "object:self]; 

In class B: first register for a notification and write a way to handle it. You give the appropriate selector to the method.

 //view did load [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil]; -(void)handleUpdatedData:(NSNotification *)notification { NSLog(@"recieved"); } 
+13
source

Of course, it is possible that the whole point of notifications. Using addObserver:selector:name:object: is how you register to receive notifications (you must do this in your table view controller), and you can use postNotificationName:object:userInfo: to publish notifications from any class.

Read non-acknowledgment programming topics for more information.

+2
source

You can register to view notifications in any number of classes. You just need to rinse and repeat. Turn on the code to register as an observer in the view controller (possibly in viewWillAppear :), and then reload the tableView from your method:

 - (void)viewWillAppear:(BOOL)animated { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(something:) name:@"something" object:nil]; } -(void)something:(NSNotification *) notification { [self.tableView reloadData]; } 

It is also a good idea to refuse to register a view controller if you no longer need notifications:

 - (void)viewWillDisappear:(BOOL)animated { [[NSNotificationCenter defaultCenter] removeObserver:self]; } 
+2
source

You should simply add this as an Observer and specify a different selector method if you want the viewController to viewController differently when this notification is sent.

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingOtherThing:) name:@"something" object:nil]; -(void)somethingOtherThing:(NSNotification *) notification { // do something } 
+1
source

Source: https://habr.com/ru/post/895361/


All Articles