3lvis / DATAStack

100% Swift Simple Boilerplate Free Core Data Stack. NSPersistentContainer
Other
214 stars 44 forks source link

Feature/new main context/swift 2.3 #85

Closed Sorix closed 7 years ago

Sorix commented 7 years ago

Okay, I've tested my new method and found strange behaviour that I can't fight. Maybe you can help me.

    public func newMainContext() -> NSManagedObjectContext {
        let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        context.name = "new main context"
        context.persistentStoreCoordinator = self.persistentStoreCoordinator
        context.undoManager = nil
        context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DATAStack.newMainContextDidSave(_:)), name: NSManagedObjectContextDidSaveNotification, object: context)

        return context
    }

    func newMainContextDidSave(notification: NSNotification) throws {
        if !NSThread.isMainThread() {
            throw NSError(info: "New Main context saved in the background thread. Use context's `performBlock`", previousError: nil)
        } else {
            let contextBlock: @convention(block) () -> Void = {
                self.mainContext.mergeChangesFromContextDidSaveNotification(notification)
            }

            let blockObject : AnyObject = unsafeBitCast(contextBlock, AnyObject.self)
            self.mainContext.performSelector(DATAStack.performSelectorForBackgroundContext(), withObject: blockObject)
        }
    }

I'm adding observer here that will fire selector DATAStack.newMainContextDidSave, also I've given the name to context for debugging purpose.

But some times that context fires backgroundContextDidSave(notification: NSNotification) method and application raises an exception. It can't fire that method because I haven't binded Notification's object to this method, but it does.

Also I've checked Notification's context's name, at it's "new main context", how can it trigger backgroundContextDidSave?

I've lost several hours but can't find the reason why that's happening, @3lvis if you have some minutes can you say why such behavior is possible?

3lvis commented 7 years ago

I think your newMainThread has to propagate changes to the writerContext. https://github.com/3lvis/DATAStack/blob/master/Source/DATAStack.swift#L254-L276