Search code examples
iosobjective-cnotificationsnsnotificationcenter

NSNotification - observer not match


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?


Solution

  • 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: