Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I watch an NSNotification from another class?

I'm trying to get my head around NSNotificationCenter. If I have something like this in my App Delegate:

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

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

}

Can I somehow watch this in another view controller? In my case, I'd like to watch it in a view controller with a table, and then reload the table when a notification is received. Is this possible?

like image 553
cannyboy Avatar asked Aug 18 '11 20:08

cannyboy


Video Answer


2 Answers

Yes you can do it like this:

In class A : post the notification

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

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

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


-(void)handleUpdatedData:(NSNotification *)notification {
    NSLog(@"recieved");
}
like image 167
JonasG Avatar answered Sep 23 '22 08:09

JonasG


Yes you can that is the whole purpose of NSNotification, you just have to add the View Controller you want as an observer exactly the same way you did on your App Delegate, and it will receive the notification.

You can find more information here: Notification Programming

like image 41
Oscar Gomez Avatar answered Sep 25 '22 08:09

Oscar Gomez