如何在SWIFT 5中使用添加观察者闭包方法移除观察者 [英] How to removeObserver in Swift 5 using addObserver closure method

查看:22
本文介绍了如何在SWIFT 5中使用添加观察者闭包方法移除观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇帖子。 我是日本的iOS工程师(这个月刚成为工程师)。

我在SWIFT 5中使用NotificationCenterremoveObserver方法有问题。

我使用闭包类型addObserver向ViewController(VC)添加了观察者。 当VC的取消初始化调用时,我要删除此观察程序。

我用VC的deinit方法编写了NotificationCenter.default.removeObserver(self)。但是,这似乎对我不起作用。

有什么问题?

此外,如果我的代码有内存泄漏问题,请让我知道如何修复它。

这是我的代码片段。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] notification in

            guard let self = self else { return }
            self.loadWeather(notification.object)
        }
    }
    
    deinit {
        print(#function)
        print("ViewController died")

        NotificationCenter.default.removeObserver(self)
    }
}

推荐答案

将您的观察器对象设置为当前视图控制器。

来自apple doc.s,对象为

观察者希望接收其通知的对象;即, 只有此发件人发送的通知才会传递给观察者。

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification,
                                       object: self,
                                       queue: nil) { [weak self] notification in
    guard let self = self else { return }
    self.loadWeather(notification.object)
}

NotificationCenter中删除观察者

deinit {
    NotificationCenter.default.removeObserver(self)
}

另一种方式

您还可以复制通知观察器对象,并将其从deinit中的NotificationCenter中删除。

let notificationCenter = NotificationCenter.default
var loadWeatherObserver: NSObjectProtocol?

override func viewDidLoad() {
    super.viewDidLoad()
    loadWeatherObserver = notificationCenter.addObserver(forName: UIApplication.didBecomeActiveNotification,
                                                         object: nil,
                                                         queue: nil) { [weak self] notification in
        guard let self = self else { return }
        self.loadWeather(notification.object)
    }
}

deinit {
    if (loadWeatherObserver != nil) {
        notificationCenter.removeObserver(loadWeatherObserver!)
    }
}

这篇关于如何在SWIFT 5中使用添加观察者闭包方法移除观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆