Search code examples
objective-cnsnotification

Crash when posting NSNotification after In-App Purchase


I am very familiar with notifications but I get a crash without any reason, after using the In-App Purchase (I doubt that it relates to it anyway).

So when the user is done purchasing,this function is being called :

- (void)provideContentForProductIdentifier:(NSString *)productIdentifier
{
     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:IAPHelperProductPurchasedNotification object:productIdentifier userInfo:nil];

    // i get the crash here when trying to post the notification.
 }

Now ,the main scene that has the observer, is setted on start with :

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productPurchased:) name:IAPHelperProductPurchasedNotification object:nil];

Is it because the object set to nil on the observer? what should it be ?


Solution

  • This problem could occur because you have an nil object as an NSNotification observer.

    It is often good remove self from the NSNotificationCenter's observer list when the object deallocates.

    Add this

    - (void) dealloc  {
      [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    in all classes that is an observer for notifications. (Note that there might be other places that you want to remove the observer. E.g. in viewDidDisappear)