Curnelious
Curnelious

Reputation: 1

NSNotificationCenter is not working?

as i told here i am using NSNotificationCenter .

on class A (observer) on the init method i have got :

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

on classB i have got :

//FILL NSDICTIONARY WITH DATA
    [dict setObject:@"SPOT1" forKey:[array objectAtIndex:0]];
    [dict setObject:@"SPOT2" forKey:[array objectAtIndex:1]];
    [dict setObject:@"SPOT3" forKey:[array objectAtIndex:2]];
    [dict setObject:@"SPOT4" forKey:[array objectAtIndex:3]];
    [dict setObject:@"SPOT5" forKey:[array objectAtIndex:4]];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"HotSpotTouched" object:dict];

the function in class A getSensorsData is not being called.

whats wrong here ??

thanks !

Upvotes: 0

Views: 3476

Answers (3)

Curnelious
Curnelious

Reputation: 1

problem solved:

if you passing a null argument, the observer is not getting the call !

my NSDictionary argument was null( because a reason i still dont know), so the call is not fired.

Upvotes: -1

Benedict Cohen
Benedict Cohen

Reputation: 11920

The calls to the notification center look correct. I suspect the problem is due to the liffe cycle of object A. You say that you're registering for the notification in the init method. Have you correctly assigned self?:

-(id)init
{
    //self does not have a meaningful value prior to the call to [super init]
    self = [super init];
    if (self != nil)
    {
        //ensure addObserver is called in the if code block
    }
    return self;
}

Also, it's good practice to use constants for notification names as they mitigate against typos. See Constants in Objective C.

Upvotes: 3

Thomas Zoechling
Thomas Zoechling

Reputation: 34263

You are passing in dict as notificationSender when posting the notification, and nil when you add the observer. This way your notification is filtered out because the senders mismatch.

Update:
As pointed out by joerick in the comments, passing nil when adding an observer will disable sender filtering. So this isn't the problem here.

I just created a small sample project and for me notifications are delivered.

@Rant: If you want to pass arbitrary data along with your notification, you should use the userInfo dictionary (as pointed out by Cyrille in the comment).

Upvotes: 3

Related Questions