So far I have been using NSNotificationCenter with the method postNotification:aString object:anyObjectOfInterestForTheReceiver. But recently I read in the documentation that the object field should only be passed self. Is there any terrible side effect I am unaware of that should convince me to only pass self in the future, or is it OK to pass any object?
Thank you!
So far I have been using NSNotificationCenter with the method postNotification:aString object:anyObjectOfInterestForTheReceiver . But
Share
You can pass any object as the
objectof a notification, but the convention is that theobjectis the “thing that is doing the notifying” (and you put other relevant state in theuserInfodictionary).The reason why it’s mostly
selfis because usually the object doing the notifying usually wants to reference itself. That way, for example, if you had manyFooobjects, and one of them completed a task and sent a notification, anyone observing the notification could just look atobjectto see whichFoowas the one in question. The observer can also choose to observe only notifications from a particularFoowhen you follow this scheme.It’s also reasonable (though less common) to use something besides “self” when posting a notification– let’s say you’re sending a notification “on behalf of” another object. For example, you could be a singleton controller object that completes a
Bartask, and you could send the notification with a reference to the particularBaras the object. That makes more sense than using the singleton as theobject, since there’d be no interesting variance there.Again, this is a (useful) convention only. When you make up your own notification, you get to define the “contract” of the notification, which is the name, what kind of object is used as the
object, and what’s in theuserInfo.