0

I use NSNotificationCenter:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playNow:) name:@"PlayNow" object:nil];

and Post:

[[NSNotificationCenter defaultCenter] postNotificationName:@"PlayNow" object:nil userInfo:noteInfoDictionary];

where self is instance of @interface MyPlayer : NSObject

And when I call it works great with most cases, but when i dealloc and alloc back MyPlayer instance i'm getting this error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView playNow:]: unrecognized selector sent to instance 0x8929150'

How it's possible that i'm getting error from UIView?

Jakub
  • 13,712
  • 17
  • 82
  • 139

2 Answers2

2

You have to remove the observer in dealloc:

[[NSNotificationCenter defaultCenter] removeObserver:self]
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
1

The problem is that you have to remove the object as observer when you dealloc it:

[[NSNotificationCenter defaultCenter] removeObserver:self]

This happens because when dealloc / init another object, the "playNow" method is called to the deallocated instance:

MyPlayer[1] init
MyPlayer[1] addObserver
MyPlayer[1] dealloc

MyPlayer[2] init
MyPlayer[2] addObserver

< POST NOTIFICATION >

The notification will call both:

MyPlayer[1] playNow:    <-- It is causing you the error, because is deallocated
MyPlayer[2] playNow:
Marco Pace
  • 3,820
  • 19
  • 38