Question

Alors j'ai une application avec un achat In App. In App Purchase est géré FirstViewController. Lorsque l'utilisateur a acheté le produit, je veux envoyer une notification à mon MainTableViewController pour recharger les données de tables et de montrer les nouveaux objets qui ont été achetés dans l'achat In App. Donc, fondamentalement, je veux envoyer une notification de la classe A à la classe B et classe B rechargements les données du tableview alors. Je l'ai essayé d'utiliser NSNotificationCenter, mais sans succès, mais je sais que son possible avec NSNotificationCenter je ne sais pas comment.

Était-ce utile?

La solution

Dans la classe A: afficher la notification

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

Dans la classe B: registre d'abord pour la notification, et d'écrire une méthode pour gérer
. Vous donnez le sélecteur correspondant à la méthode.

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

-(void)handleUpdatedData:(NSNotification *)notification {
    NSLog(@"recieved");
    [self.tableView reloadData];
}

Autres conseils

Ok I'm adding a little bit more information to vince's answer

In class A : post the notification

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

In class B : register first for the notification, and write a method to handle it.
You give the corresponding selector to the method. Make sure your class B is allocated before you post the notification otherwie 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];
 }

Maybe you trying to send notification from another thread? NSNotification won't be delivered to the observer from another thread.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top