From b4903edbd389927d67a3b843b76fec5bdf82febf Mon Sep 17 00:00:00 2001 From: Brad Slayter Date: Thu, 19 Sep 2024 08:33:29 -0500 Subject: [PATCH] Track calls to add/remove file presenter --- .../DefaultConfigurationManager.swift | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Sources/Configuration/DefaultConfigurationManager.swift b/Sources/Configuration/DefaultConfigurationManager.swift index 89eddea27..b2373b2aa 100644 --- a/Sources/Configuration/DefaultConfigurationManager.swift +++ b/Sources/Configuration/DefaultConfigurationManager.swift @@ -62,16 +62,18 @@ open class DefaultConfigurationManager: NSObject { public var fetcher: ConfigurationFetching public var store: ConfigurationStoring + private var filePresenterCount: Int = 0 + public init(fetcher: ConfigurationFetching, store: ConfigurationStoring, defaults: KeyValueStoring) { self.fetcher = fetcher self.store = store self.defaults = defaults super.init() - NSFileCoordinator.addFilePresenter(self) + addPresenter() } deinit { - NSFileCoordinator.removeFilePresenter(self) + removePresenter() } public static let queue: DispatchQueue = DispatchQueue(label: "Configuration Manager") @@ -94,6 +96,22 @@ open class DefaultConfigurationManager: NSObject { } public var lastRefreshCheckTime: Date = Date() + /// Calls to `addFilePresenter` and `removeFilePresenter` must be balanced + /// We'll use `filePresenterCount` to ensure we're properly managing this. + @objc public func addPresenter() { + guard filePresenterCount == 0 else { return } + NSFileCoordinator.addFilePresenter(self) + filePresenterCount += 1 + } + + @objc public func removePresenter() { + guard filePresenterCount > 0 else { return } + while filePresenterCount > 0 { + NSFileCoordinator.removeFilePresenter(self) + filePresenterCount -= 1 + } + } + public func start() { Logger.config.debug("Starting configuration refresh timer") refreshTask = Task.periodic(interval: Constants.refreshCheckIntervalSeconds) {