objective-ciosnsnotificationcenternsnotification

Send NSNotification from classA to classB


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.


Solution

  • 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];
    }