2017-03-10 2 views
5

이상한 문제가 있습니다. 나는 다음과 같이 내 알림을 등록 및 등록 취소합니다.알림을위한 removeObserver Swift3

func doRegisterNotificationListener() { 
     NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "RateAlertRated"), object: nil, queue: nil, using: rateDidRate) 
    } 

    func doUnregisterNotificationListener() { 
     NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "RateAlertRated"), object: nil) 
    } 

    func rateDidRate(notification: Notification) { 
     let rating = notification.userInfo?["score"] as? Int 
     let message = notification.userInfo?["message"] as? String 
     let response = Response(rating: rating, message: message) 
     output.presentRated(response) 
    } 

이보기 컨트롤러는 UITabBarController에 있습니다. doRegisterNotificationListenerviewDidAppear에 있고 doUnregisterNotificationListenerviewDidDisappear에 호출되었습니다. 탭간에 전환 할 때 register 및 unregister 메서드가 올바르게 호출되고 있습니다 (print 문을 사용하여 테스트했습니다). 그러나 알림을 실행하면 doUnregisterNotificationListener이 마지막으로 호출 되었더라도 계속 수신됩니다. 내가 여기서 잘못하고있는 아이디어가 있습니까?

빠른 참고 : 또한 시도

는 :

NotificationCenter.default.removeObserver(self) 

이 또한 작동하지 않습니다. 당신이 addObserver(forName:object:queue:using:)로 작업하는 경우

+0

당신은 또한 관찰자로의 ViewController를 제거 할 수있는 것은 deinit 방법에 NotificationCenter.default.removeObserver (자신을)이 시도 – Pankaj

+0

@Prince 그와 차이 – KexAri

답변

1

코드를 테스트 한 후이 유형의 관찰자를 등록하면 등록을 취소 할 때 호출되지 않습니다. 이것을 시도하십시오.

NotificationCenter.default.addObserver(self, selector: #selector(rateDidRate(notification:)), name: Notification.Name(rawValue: "RateAlertRated"), object: nil) 
+0

모든 코드를 테스트하려는 경우 다음 내가 여기에 게시 할 수 시도하지 않습니다. – Pankaj

+0

우수. 이것은 지금 일하고있다. 또한 셀렉터 기능을 '동적'으로 만드는 것을 기억해야합니다. – KexAri

+0

좋은 일을 당신을 위해. – Pankaj

1

이 방법으로 제거해야합니다

만들기 :

let center = NSNotificationCenter.defaultCenter() 
let mainQueue = NSOperationQueue.mainQueue() 
self.localeChangeObserver = center.addObserverForName(NSCurrentLocaleDidChangeNotification, object: nil, queue: mainQueue) { (note) in 
    print("The user's locale changed to: \(NSLocale.currentLocale().localeIdentifier)") 
} 

제거 :

center.removeObserver(self.localeChangeObserver) 

이러한 접근 방식은 documentation에서 가져옵니다.