3lvis / DATAStack

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

EXC_BAD_ACCESS on main thread #83

Closed duzvik closed 8 years ago

duzvik commented 8 years ago

Hello, Any ideas this code fails(EXC_BAD_ACCESS on save()), but with performBlock working OK?

let backgroundContext = App.sharedInstance.dataStack.newBackgroundContext()

let request: NSFetchRequest = NSFetchRequest(entityName: "UserSettings")

let fetched = try!  backgroundContext.executeFetchRequest(request) as? [UserSettings]

let record = fetched!.first!

record.setValue(NSDate(), forKey: "updatedAt")

    backgroundContext.performBlockAndWait({

      try! backgroundContext.save()

    })
3lvis commented 8 years ago

I think your problem is that you're fetching the item in the main thread and storing it in a background thread, so it gets deallocated.

Could you try this instead?

self.dataStack.performInNewBackgroundContext { backgroundContext in
    let request = NSFetchRequest(entityName: "UserSettings")
    let fetched = try! backgroundContext.executeFetchRequest(request) as? [UserSettings]
    let record = fetched!.first!
    record.setValue(NSDate(), forKey: "updatedAt")
    try! backgroundContext.save()
}

In general lines use

self.dataStack.performInNewBackgroundContext { backgroundContext in

The other method is reserved for very special cases such as usage in NSOperation where everything is concurrent.

3lvis commented 8 years ago

Hopefully this fixes your issue, otherwise let me know.

Have a nice weekend!