Question

When I comment out...

// [[NSNotificationCenter defaultCenter] removeObserver:self name:@"LoadRequestFromAppDel" object:Nil];

...my app works as expected, the notification center works time and time again.

But when I UNCOMMENT it, so it actually runs in my code, my app will work fine ONCE, but the second time I try to repeat it - it simply does not trigger.

I was told to make sure to "removeObserver", but when I do this my app stops working as intended, so do I just get rid of this removeObserver code? Or is there a different way to handle this?

(My app is detecting if urlscheme:// is pushtap:// and then it sends the url to another view via notification center, and then it tries to removeObserver after its done... problem is, it only does this one time if I have the removeObserver added, the second time I try to use pushtap:// from safari it simply does not run the code again - unless of course I get rid of the removeObserver line I showed above.)

Was it helpful?

Solution 2

You need to observe when the view appears:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mySelector:) name:@"MyNotification" object:nil];
}

Then you can remove your observer when the view disappears:

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

This way you don't leave observers that can't respond anyway since they aren't onscreen.

OTHER TIPS

You need to call removeObserver when you no longer need to listen for that notification, if you do this when your viewController disappears then you need to re add the observer when it appears again.

Removing observer will do exactly that. In your case you want to keep observing so you can afford to delete that line.

I suggest moving that line of code to inside your dealloc method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top