Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter removeObserver not working

-(void)viewDidAppear:(BOOL)animated {
            NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
                [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {
                    NSLog(@"SShot");
            }];
        }

- (void)viewWillDisappear:(BOOL)animated{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    NSLog(@"VWD");
        }

 -(void)viewDidDisappear:(BOOL)animated {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
        NSLog(@"VDD");
    }

I am getting SShot logged in console even after I have removed the observer.

Is there any other way to remove UIApplicationUserDidTakeScreenshotNotification observer.

like image 981
S.J Avatar asked Oct 28 '15 10:10

S.J


3 Answers

Harris code is correct except a small detail that for Swift 4 it is now

private var observer: Any! and not private var observer: NSObjectProtocol! So code should be:

private var observer: Any!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
        //do something
    }
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(observer)
}
like image 191
Zebra Avatar answered Nov 15 '22 22:11

Zebra


Here is how to do it in Swift 4...

    private var observer: Any!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
            //do something
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(observer)
    }
like image 35
Elijah Avatar answered Nov 15 '22 22:11

Elijah


From Apple Doc:

To unregister observations, you pass the object returned by this method to removeObserver:. You must invoke removeObserver: or removeObserver:name:object: before any object specified by addObserverForName:object:queue:usingBlock: is deallocated.

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];

You're trying to remove the worng observer, self is not the observer here, the observer is the object returned by the add method

like image 33
Leonardo Avatar answered Nov 15 '22 22:11

Leonardo