Skip to content

Commit

Permalink
fix: 修复多次打开首选项窗口会导致内存泄漏的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
qwertyyb committed Jun 28, 2022
1 parent 7a575fb commit 093d8f7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 deletions.
10 changes: 4 additions & 6 deletions Fire/Preferences/FirePreferencesController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class FirePreferencesController: NSObject, NSWindowDelegate {
private var controller: PreferencesWindowController?
static let shared = FirePreferencesController()

var isVisible: Bool {
controller?.window?.isVisible ?? false
}

func show() {
if let controller = controller {
controller.show()
Expand Down Expand Up @@ -61,10 +65,4 @@ class FirePreferencesController: NSObject, NSWindowDelegate {
self.controller?.window?.delegate = self
self.controller?.show()
}

func windowWillClose(_ notification: Notification) {
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
self.controller = nil
}
}
}
34 changes: 20 additions & 14 deletions Fire/Preferences/StatisticsPane.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,15 @@ class DateCountData: ObservableObject {
@Published var total: Int64 = 0

var cancellables = Set<AnyCancellable>()
private var observer: Any?

init() {
refresh()
observer = NotificationCenter.default.addObserver(
self,
selector: #selector(refresh),
name: Statistics.updated,
object: nil
)
NotificationCenter.default
.publisher(for: Statistics.updated)
.sink { _ in
self.refresh()
}
.store(in: &cancellables)
$startDate.sink { date in
self.refreshData(startDate: date, endDate: nil)
}
Expand All @@ -77,21 +76,28 @@ class DateCountData: ObservableObject {
}

deinit {
guard let observer = self.observer else {
return
cancellables.forEach { cancellable in
cancellable.cancel()
}
NotificationCenter.default.removeObserver(observer)
self.observer = nil
cancellables = []
}

@objc func refresh() {
NSLog("[DateCountData] refresh start: \(startDate)")
if !FirePreferencesController.shared.isVisible {
NSLog("[DateCountData] refresh cancel: not visible")
return
}
total = Statistics.shared.queryTotalCount()
self.refreshData(startDate: nil, endDate: nil)
}

func refreshData(startDate: Date?, endDate: Date?) {
data = Statistics.shared.queryCountByDate(startDate: startDate ?? self.startDate, endDate: endDate ?? self.endDate)
data = Statistics.shared
.queryCountByDate(
startDate: startDate ?? self.startDate,
endDate: endDate ?? self.endDate
)
}

func clear() {
Expand All @@ -100,7 +106,7 @@ class DateCountData: ObservableObject {
}

struct StatisticsPane: View {
@ObservedObject var dateCountData = DateCountData()
@StateObject var dateCountData = DateCountData()
@Default(.enableStatistics) private var enableStatistics
@State private var showAlert = false

Expand Down

0 comments on commit 093d8f7

Please sign in to comment.