From d204b03633bdbe8dfea5645893b52a4d828545e5 Mon Sep 17 00:00:00 2001 From: Tony Li Date: Fri, 30 Jun 2023 19:47:24 +1200 Subject: [PATCH] Retain a notification observer in StatsForegroundObservable --- .../Stats/StatsForegroundObservable.swift | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/WordPress/Classes/ViewRelated/Stats/StatsForegroundObservable.swift b/WordPress/Classes/ViewRelated/Stats/StatsForegroundObservable.swift index 447af1b75cf2..63d45d12e1ef 100644 --- a/WordPress/Classes/ViewRelated/Stats/StatsForegroundObservable.swift +++ b/WordPress/Classes/ViewRelated/Stats/StatsForegroundObservable.swift @@ -4,9 +4,11 @@ protocol StatsForegroundObservable: AnyObject { func reloadStatsData() } +private var observerKey = 0 + extension StatsForegroundObservable where Self: UIViewController { func addWillEnterForegroundObserver() { - NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, + enterForegroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in self?.reloadStatsData() @@ -14,8 +16,18 @@ extension StatsForegroundObservable where Self: UIViewController { } func removeWillEnterForegroundObserver() { - NotificationCenter.default.removeObserver(self, - name: UIApplication.willEnterForegroundNotification, - object: nil) + if let enterForegroundObserver { + NotificationCenter.default.removeObserver(enterForegroundObserver) + } + enterForegroundObserver = nil + } + + private var enterForegroundObserver: NSObjectProtocol? { + get { + objc_getAssociatedObject(self, &observerKey) as? NSObjectProtocol + } + set { + objc_setAssociatedObject(self, &observerKey, newValue, .OBJC_ASSOCIATION_RETAIN) + } } }