Send NSNotification from classA to classB

JonasG picture JonasG · Jul 25, 2011 · Viewed 11.5k times · Source

So i have an app with an In App purchase. The In App purchase is managed in FirstViewController. When the user has purchased the product, i want to send out a Notification to my MainTableViewController to reload the tables data and show the new objects that were purchased in the In App purchase. So basically i want to send a notification from class A to class B and class B reloads the data of the tableview then. I have tried using NSNotificationCenter, but with no success, but i know that its possible with NSNotificationCenter i just don't know how.

Answer

user756245 picture user756245 · Jul 25, 2011

In class A : post the notification

[[NSNotificationCenter defaultCenter] postNotificationName:@"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");
    [self.tableView reloadData];
}