Browse Source

Reap dead observer boxes when registering with the broadcaster

Nothing ever removed deallocated observers' WeakObject boxes, so the
process-wide observer sets grew on every screen open/close. Compact the
set on every add — re-registration reaps the boxes previous instances
left behind.
Marvin Polscheit 1 day ago
parent
commit
8ac5b26a7d

+ 8 - 0
Trio/Sources/Services/Notifications/SwiftNotificationCenter/WeakObjectSet.swift

@@ -41,6 +41,9 @@ struct WeakObjectSet<T: AnyObject>: Sequence {
     }
 
     mutating func add(_ object: T) {
+        // Registration doubles as the reaping hook — dead boxes are removed nowhere
+        // else, and most observers never unregister explicitly.
+        compact()
         // prevent ObjectIdentifier be reused
         if contains(object) {
             remove(object)
@@ -48,6 +51,11 @@ struct WeakObjectSet<T: AnyObject>: Sequence {
         objects.insert(WeakObject(object))
     }
 
+    /// Drops entries whose weakly-held object has been deallocated.
+    mutating func compact() {
+        objects = objects.filter { $0.object != nil }
+    }
+
     mutating func add(_ objects: [T]) {
         objects.forEach { self.add($0) }
     }