0

As the title described.

I want to prevent duplicated observer adding so that the selector would not be called twice.

Andrew Chang
  • 1,289
  • 1
  • 18
  • 38

1 Answers1

2

No, it's not possible. You can either call removeObserver method just before adding observer to make sure you didn't add it twice or subclass NSNotificationCenter and register all observers yourself.

P.S. Have you tried adding observer twice? Is your selector also called twice?

Stas
  • 641
  • 8
  • 16
  • Yes, I added twice and observed two notification calls. However, if I remove a observer that I have not added before, error occurs. Looks like I should add a BOOL variable to achieve such check. – Andrew Chang Aug 06 '13 at 08:54
  • It might help. But why do you ever need such behaviour? Pattern seems simple - add observer in `viewDidLoad` and remove in `viewDidUnload`. – Stas Aug 06 '13 at 09:01
  • Observer may be assign to the view's controller before **OR** after it was loaded, depends on user's need. I would add observer as soon as all conditions are met in both methods. This may cause duplicated adding. – Andrew Chang Aug 06 '13 at 09:14
  • You could use the `observationInfo` method from NSObject. `- observationInfo Returns a pointer that identifies information about all of the observers that are registered with the receiver.` – Erwan Nov 14 '14 at 07:10
  • Stas, Yes, you might need such behavior. There are all kinds of other objects besides view controllers that may need to be registered as an observer. – Alyoshak Oct 30 '18 at 17:24