Send NSNotification from classA to classB

So, I have an In App purchase app. In App Purchases are managed in FirstViewController. When a user purchases a product, I want to send a notification to my MainTableViewController to reload the table data and show new objects that were purchased when I purchased In App. So basically I want to send a notification from class A to class B, and class B then loads the table data. I tried to use NSNotificationCenter, but without success, but I know that its possible with NSNotificationCenter I just don't know how to do it.

+4
source share
3 answers

In class A: post a notice

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

Ok i am adding a bit more info to answer vince

In class A: post a notice

 [[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdated" object:arrayOfPurchasedObjects]; 

In class B: first register for a notification and write a way to handle it.
You give the appropriate selector to the method. Make sure your class B is assigned before you send a notification, another notification will not work.

 - (void) viewDidLoad { // view did load [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil]; } -(void)handleUpdatedData:(NSNotification *)notification { NSLog(@"recieved"); NSArray *purchased = [notification object]; [classBTableDataSourceArray addObjectsFromArray:purchased]; [self.tableView reloadData]; } - (void) dealloc { // view did load [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DataUpdated" object:nil]; [super dealloc]; } 
+8
source

Maybe you are trying to send a notification from another thread? NSNotification will not be delivered to the observer from another stream.

0
source

All Articles