objective-cfoundationnsnotifications

Is it safe to pass a notification (NSNotification) as a userInfo of another notification?


I have an object that responds to a list of notifications (A,B,C...). Each response ends with posting a new notification (X) to other listeners. I want to include the old/original notification - I mean the whole NSNotification instance - as a value into the userInfo dictionary of the new notification (X). Is this safe?

(My intuition is that it is not, but I do not see any particular problem other than, perhaps some circular references, if the dictionary contents are not handled carefully).


Solution

  • It's safe to include an NSNotification instances as a value in the userInfo dictionary of another. There's really no magic in NSNotification itself. It's a pretty simple/thin model class representing a notification*. As you mention you will want to avoid retain cycles, by e.g. including two notifications in each others user info dictionaries at the same time. Even then, the worst that will happen is a (small for just two notifications) memory leak.

    *Technically NSNotification is an abstract class cluster, and when you instantiate an NSNotification directly you actually get an instance of the private NSConcreteNotification (as of macOS 10.15.1), but this doesn't affect the answer to your question.