Skip to content
This repository was archived by the owner on Feb 8, 2023. It is now read-only.

Commit 87b4c6e

Browse files
author
Erik Luimes
committed
Fixes: Fatal error: Attempted to read an unowned reference but the object was already deallocated
1 parent f2edbd9 commit 87b4c6e

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

CoreDataKit/ManagedObjectObserver.swift

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,35 +52,39 @@ public class ManagedObjectObserver<T:NSManagedObject>: NSObject {
5252
self.subscribers = [Subscriber]()
5353
super.init()
5454

55-
notificationObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: context, queue: nil) { [unowned self] notification in
55+
notificationObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: context, queue: nil) { [weak self] notification in
56+
guard let strongSelf = self else {
57+
return
58+
}
59+
5660
context.perform {
57-
if self.subscribers.isEmpty {
61+
if strongSelf.subscribers.isEmpty {
5862
return
5963
}
6064

6165
do {
62-
let convertedObject = try context.find(T.self, managedObjectID: self.observedObject.objectID)
66+
let convertedObject = try context.find(T.self, managedObjectID: strongSelf.observedObject.objectID)
6367
if let updatedObjects = (notification as NSNotification).userInfo?[NSUpdatedObjectsKey] as? NSSet {
6468
if updatedObjects.contains(convertedObject) {
65-
self.notifySubscribers(.updated(convertedObject))
69+
strongSelf.notifySubscribers(.updated(convertedObject))
6670
}
6771
}
6872

6973
if let refreshedObjects = (notification as NSNotification).userInfo?[NSRefreshedObjectsKey] as? NSSet {
7074
if refreshedObjects.contains(convertedObject) {
71-
self.notifySubscribers(.refreshed(convertedObject))
75+
strongSelf.notifySubscribers(.refreshed(convertedObject))
7276
}
7377
}
7478

7579
if let insertedObjects = (notification as NSNotification).userInfo?[NSInsertedObjectsKey] as? NSSet {
7680
if insertedObjects.contains(convertedObject) {
77-
self.notifySubscribers(.inserted(convertedObject))
81+
strongSelf.notifySubscribers(.inserted(convertedObject))
7882
}
7983
}
8084

8185
if let deletedObjects = (notification as NSNotification).userInfo?[NSDeletedObjectsKey] as? NSSet {
8286
if deletedObjects.contains(convertedObject) {
83-
self.notifySubscribers(.deleted)
87+
strongSelf.notifySubscribers(.deleted)
8488
}
8589
}
8690
}

0 commit comments

Comments
 (0)