Search code examples
iphoneiosnsnotificationcenter

NSNotificationCenter: how can I tell what posted the notification?


I have an NSNotification observer in class A named Test. The observer calls a method, checker:

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

Then I have two posts in classes B and C, both to the observer named Test

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

I'd like to be able to know which post is being sent to the observer and increment a counter to be usable in the check method, something like:

-(void)check {
    if ([classB count] <= [classC count]) {
        NSLog(@"boom");
    }
}

I've seen suggestions to use the userinfo to do so but im not quite sure how; is the counter object instantiated in class B/C and passed as an int or dictionary etc

Any help greatly appreciated Thanks


Solution

  • Well you need to have your counter in class A. Than you can do this in checker: function

    - (void)checker:(NSNotification *)notification
    {
        if ([notification.object isKindOfClass:[BClass class]]) {
            bCounter++;
        }
        else if ([notification.object isKindOfClass:[CClass class]]) {
            cCounter++;
        }
    
        if (bCounter < cCounter) {
            NSLog(@"boom");
        }
    }
    

    Let me know if it works for you.