3

I'm using NSNotificationCenter to send custom notifications in a document-based app.

A document-based app can have many open documents. Ideally, I would like the the document and its children to receive only the notifications created within the document or its children. In other words, a document should receive only the notifications that the same document generates.

At first I thought I could use the notificationSender parameter of addObserver:selector:name:object: but then I realised that I don't always know which object will send the notification.

Do I have to check if I'm in the right document for every custom notification? Is there a better way to do this?

hpique
  • 119,096
  • 131
  • 338
  • 476

2 Answers2

3

I think that your approach works if you use the main document as notificationSender argument for both addObserver:selector:name:object: and postNotificationName:object:.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • That's what I first tried. But if I do that I can't send the real sender (some object related to document that generates the notification). – hpique Sep 04 '12 at 20:51
  • @hpique: Perhaps you can use the `userInfo` parameter to pass the real sender? – Martin R Sep 04 '12 at 21:24
2

You can define a NotificationCenter in your NSDocument class and use that to post notifications within a document (Swift):

class Document: NSDocument {

    let notificationCenter = NotificationCenter()

    // Other stuff
}

And call it like this:

document.notificationCenter.post(name: yourNotificationIdentifier, object: nil)
Ely
  • 8,259
  • 1
  • 54
  • 67