2017-02-10 147 views
1

我使用库格尔通知库(https://github.com/TakeScoop/Kugel/tree/swift-3.0)。我想知道如何删除Observer和我的代码中的哪个位置。我使用退订图书馆并没有任何反应移除观察者通知Swift 3

覆盖FUNC viewDidDisappear(_动画:BOOL){

super.viewDidDisappear(animated) 
    Kugel.unsubscribe("SleepMode") 
    Kugel.unsubscribe("SleepModeSynchroMode") 
    Kugel.unsubscribe(self, name: NSNotification.Name(rawValue: "SleepMode"), object: nil) 
    Kugel.unsubscribe(self, name: NSNotification.Name(rawValue: "SleepModeSynchroMode"), object: nil) 
    NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "SleepMode"), object: nil); 
    NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "SleepModeSynchroMode"), object: nil); 
} 

我想删除订阅通知(添加观察者),当我回到其他视图。 我使用denit {},但没有杀死的通知。

你能helpme

Tahnks

+0

它应该工作,但请尽量将 - 优先FUNC viewDidDisappear(_动画:BOOL){ NotificationCenter.default.removeObserver(个体经营) } –

回答

0

尝试和删除观察员viewWillAppear中

+0

这应该是一个评论,不是答案! –

+0

@Div你绝对正确。它应该是。但这也是他的问题的答案 – Vandal

+2

我认为这是错误的答案。我想你的意思是'viewWillDisappear'或'viewDidDisappear'。但是如果@ user1883993的答案是正确的,那应该是被接受的答案。 –

2

如果您的应用程序的目标的iOS 9.0及更高版本或MacOS的10.11及更高版本,您不需要注销观察员在其释放方法中。如果您的应用面向早期版本,则需要保留对观察者对象的引用并提交它,而不是“自己”,库也称它已被弃用。为什么要使用它?

1

所有这些都是错误的。这里是删除Swift中观察者的正确方法(也适用于Obj-C): 根据Apple的文档,您必须保留对观察者的引用! NSNotificationCenter addObserver自我不是观察者,所以NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "SleepMode"), object: nil);不会做任何事情。 你所要做的是:

  1. 延长Notification.Name您的通知:(您发布通知)

    extension Notification.Name { 
        static let notification = Notification.Name(rawValue: "A notification") 
    } 
    
  2. 创建一个弱引用您的观测者:

    weak var observer: NSObjectProtocol? 
    
  3. 创建一个“addObserver”函数,如下所示:(您想要听通知的地方)

    func addObserver() { 
        guard observer == nil else { return } 
        observer = NotificationCenter.default.addObserver(forName: .notification, 
                    object: nil, 
                     queue: .main) { notification in 
        print("Notification triggered") 
    } 
    
  4. 创建 “removeObserver” 功能:

    func removeObserver() { 
        guard let observer = observer else { return } 
        NotificationCenter.default.removeObserver(observer) 
    } 
    
  5. 呼叫无论你需要在你的代码你 “的addObserver” 功能(从您的viewDidLoad方法最有可能)

  6. 呼叫当您完成收听该通知时,使用“removeObserver”函数。

一个重要这里的一点是,如果你有一个额外的强引用您的类执行通知和你“认为”观察者被删除,但它不是,那么guard执行上面可以防止您的代码创建几位观察员。在viewDidLoad函数中缺少removeObserver的某些addObserver实现的情况尤其如此。 证明?在分配观察者并编辑断点的线上的addObserver函数中添加一个断点(右键单击),然后选择add action并选择Sound并选择选项Automatically continue after evaluating actions

enter image description here

启动应用程序,来回走在实现观察者的观点。如果您听到声音的次数不变,就完成了!否则,你应该在这里每次进入视图时声音增加一次。你走了!