1

I am writting an SDK and looking for the best practise to send an object via NSNotification.

Apple and some threads including this indicate that the object param in postNotificationNamer should be the sender of the notification, which in most case, self. And your custom object should be passed via userInfo NSDictionary. From Apple doc:

Creates a notification with a given name, sender, and information and posts it to the receiver.

For example, the inappropriate practise is:

[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" 
                                                    object:myObject];

And the recommended way is:

NSDictionary* userInfo = @{@"myMessage": myObject};
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" 
                                                    object:self 
                                                  userInfo:userInfo];

I have tried both methods and they all work well. Question is, is there any risk to use former method? In my case I am not interested in the sender of the notification, but using the latter method introduces an additional wrapper (NSDicionary) around the actual object I want to send.

Community
  • 1
  • 1
Summer
  • 488
  • 4
  • 14

2 Answers2

3

It's not dangerous to use the object parameter, but have in mind that NSNotificationCenter uses that parameter internally to decide some things. So if your code depends on things running in certain order or certain queues, it may behave unexpectedly.

Here's the relevant quote from the NSNotificationCenter Class Reference:

The object whose notifications you want to add the block to the operation queue.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to add the block to the operation queue.

I would recommend that you used userInfo as intended, but it is not dangerous.

Community
  • 1
  • 1
NiñoScript
  • 4,523
  • 2
  • 27
  • 33
2

The latter is more flexible. While you may not care about the sender now, that could change. And you may later find you need to pass additional info.

Better to do it right upfront. It takes no extra effort to do it right the first time and it will be a lot of effort (and prone to mistakes) to have to go back and refactor a bunch of code when your needs change.

Plus, using the latter approach means your code is consistent with how it is done in other frameworks. Consistency makes code easier to read and maintain. You don't have to think about, "well in this case I get the object here, but in this case I get it there".

rmaddy
  • 314,917
  • 42
  • 532
  • 579