Re: NSNotificationCenter
Re: NSNotificationCenter
- Subject: Re: NSNotificationCenter
- From: Graham Cox <email@hidden>
- Date: Fri, 26 Sep 2008 22:37:57 +1000
On 26 Sep 2008, at 10:14 pm, John Love wrote:
Shouldn't my call to -addObserver automatically monitor
"StatusChanged" rather than my having to -postNotificationName??
Well, no.
It's not magic - something needs to "transmit" so that there is
something to "receive". All the NSNotificationCenter is is a relay
station for messages, so that observers don't need intimate knowledge
(and hence strong coupling) to the objects they are observing, and
vice versa.
The reality of sending notifications is that typically objects are
designed to blindly transmit all sorts of notifications that the
design deems useful. "This happened, that will happen" and so on. If
you have a sender A and a receiver B that set up a notification for
some single purpose the advantage of this may seem hard to see, and
you certainly don't get much "for free". But when you have a complex
object with lots of behaviours that other objects might want to
observe then the posting of notifications built into the design of
object A is great - it means you can simply observe those
notifications without revisiting the design of A - a real boon if you
don't even have its source code, as with many Cocoa objects.
So, to your case:
- (void) postCalculationStatusChanged:(id)sentNotifyObject {
[notifyCenter postNotificationName:StatusChanged
object:sentNotifyObject];
}
This violates the spirit and purpose of notifications. Your receiver
shouldn't also be forcing the "transmitter" to transmit, as you are
doing here. Instead, the transmitter object should always send a
"status changed" message whenever its status changes. Then the fact
that it has changed can be observed by the receiver *and also any
other object that might be interested*. What you're doing here is
absurd - if you already know the transmitter's status has changed,
then you can act on that directly - you don't need to pretend to send
a notification to yourself.
Somewhere, you should have some code that is part of the
'sentNotifyObject' class that looks like this:
- (void) postStatusChanged
{
[[NSNotificationCenter defaultCenter]
postNotificationName:kStatusChangedNotification object:self];
}
In almost all cases, whenever you call the -postNotificationName:
method of NSNotificationCenter, the object you pass is 'self'. If it's
any other, chances are you've done something weird.
So, short answer: your design is a bit whiffy. ;)
hth,
Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden