views:

91

answers:

1

A simplification...

A building has an array of apartment objects. Each apartment has a single currentTenant. These tenants are of type Person. Note that currentTenant doesn't have a reference to the apartment, so can't send information back up the chain.

When a tenant has a plumbing issue he raises an NSNotification:

[nc postNotificationName:@"PlumbingIssue" object:self];

Each Apartment observes notifications ONLY FROM it's own current tenant (this is set up when the apartment is built, before there is a current tenant):

[nc addObserver:self selector:@selector(alertBuildingManager:) name:@"PlumbingIssue" object:[self currentTenant];

When the apartment receives a notification from it's own currentTenant, it sends it's own notification, "PlumberRequired", along with the apartment number and the currentTenant in an NSDictionary.

Apartment observes these notifications, which it will take from any apartment (or other object):

[nc addObserver:self selector:@selector(callPlumber) name:@"PlumberRequired" object:nil];

Is there something I could be getting fundamentally wrong here? What's happening is that the apartment is receiving notifications from any and all currentTenants, rather than jus it's own.

Sorry that the actual code is a bit too unwieldy to post. Was just wondering if there's a gap in my understanding about observing notifications from a particular sender?

+1  A: 

The key bit is here:

Each Apartment observes notifications ONLY FROM it's own current tenant (this is set up when the apartment is built, before there is a current tenant)

If there's no currentTennant, then your code is actually doing this:

[nc addObserver:self selector:@selector(alertBuildingManager:) name:@"PlumbingIssue" object:nil];

When you use nil as the object parameter, you tell NSNotificationCenter you want all PlumbingIssue alerts delivered to this observer. What you'll need to do is make sure that you set up the notification only when you have a currentTennant. If you're using properties, setCurrentTennant: would probably be a good place to do this.

Do make sure to remove yourself as an observer when currentTennant changes, and always make sure to remove your object as an observer entirely when it's deallocated (or else NSNotificationCenter may try to post notifications to a deallocated object, which is a Very Bad Thing). - [NSNotifcationCenter removeObserver:] is the easiest way to do that.

Alex
Interesting. What if I could guarantee that there was always a currentTenant when the notification is posted? currentTenant changes frequently, but there is always one.
Ben Packard
It doesn't matter when the notification is posted, but when you register for the notification. If the current tenant is nil, you're registering for all PlumbingIssue notifications, from all tenants who might possibly send one. Basically, when a tenant moves in, register for his notifications; when he moves out, remove yourself from them.
Marc Charbonneau