Question

Quelqu'un pourrait-il s'il vous plaît me montrer comment utiliser la propriété d'objet sur NSNotifcationCenter. Je veux être en mesure de l'utiliser pour passer une valeur entière à ma méthode de sélection.

Voici comment je l'ai mis en place l'auditeur de notification dans mon interface utilisateur View. Voyant que je veux une valeur entière à passer Je ne sais pas quoi remplacer nul avec.

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


- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}

J'envoie la notification d'une autre classe comme celui-ci. La fonction est passée une variable index nommé. Il est cette valeur que je veux tirer en quelque sorte de la notification.

-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}
Était-ce utile?

La solution

Le paramètre object représente l'expéditeur de la notification, qui est habituellement self.

Si vous voulez transmettre des informations supplémentaires, vous devez utiliser la méthode NSNotificationCenter postNotificationName:object:userInfo:, qui prend un dictionnaire arbitraire de valeurs (que vous êtes libre de définir). Le contenu doit être réelle instances NSObject, pas un type intégral tel que un nombre entier, de sorte que vous devez envelopper les valeurs entières avec des objets NSNumber.

NSDictionary* dict = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
                                      object:self
                                      userInfo:dict];

Autres conseils

La propriété object ne convient pas pour cela. Au lieu de cela que vous voulez utiliser le paramètre userinfo:

+ (id)notificationWithName:(NSString *)aName 
                    object:(id)anObject 
                  userInfo:(NSDictionary *)userInfo

userInfo est, comme vous pouvez le voir, un NSDictionary spécifiquement pour l'envoi d'informations ainsi que la notification.

Votre méthode dispatchFunction serait plutôt quelque chose comme ceci:

- (void) disptachFunction:(int) index {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}

Votre méthode receiveEvent serait quelque chose comme ceci:

- (void)receiveEvent:(NSNotification *)notification {
    int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top