2015-10-28 58 views
2
-(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"); 
    } 

即使在我刪除了觀察者之後,我正在登錄控制檯SShotNSNotificationCenter removeObserver不能正常工作

是否有任何其他方式可以刪除UIApplicationUserDidTakeScreenshotNotification觀察者。

回答

7

Apple Doc

要註銷的意見,你傳遞對象通過該 方法removeObserver返回 :.您必須調用removeObserver:或 removeObserver:name:object:在由 指定的任何對象之前addObserverForName:object:queue:usingBlock:將被釋放。

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

你試圖刪除撥錯觀察者,self是不是這裏的觀察者,觀察者

+1

非常感謝... –

0

嘗試使用此代碼

通過add方法返回的對象添加觀察

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil]; 
} 

- (void)userDidTakeScreenshot { 
    // Screenshot taken, act accordingly. 
} 

而對於刪除特定觀察

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

刪除所有觀察員

- (void)viewWillDisappear:(BOOL)animated { 
     [super viewWillDisappear:animated]; 
     [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    } 

讓我知道它的工作適合你!!!!

6

這裏是如何做到這一點的斯威夫特3

fileprivate var observer: NSObjectProtocol! 

    override func viewWillAppear(_ animated: Bool) { 
     super.viewWillAppear(animated) 
     observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil, using: someFunction) 
    } 

    override func viewDidDisappear(_ animated: Bool) { 
     super.viewDidDisappear(animated) 
     NotificationCenter.default.removeObserver(observer) 
    } 

    func someFunction(notification: Notification) { 
    }