Reputation: 115
I have very simple app, that has a CoreData database and in it, it has two type of objects, one that is the main object, and the other. The main object, Object A, can have many Object B. But Object B, can be connected to only one Object A.
My problem is, after a while of the app running, it runs into EXC_BAD_ACCESS
error.
To be precise:
Thread 85: EXC_BAD_ACCESS (code=1, address=0x77e341213c20)
I have done some debugging, and it looks like this only happens, when I open the SwiftUI part of the interface, and possibly make changes to the db. I have read in forums, that it's a Thread issue and access. I tried database setup mentioed there (I am copying here) but that still runs into the error.
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
return result
}()
var context: NSManagedObjectContext {
return container.viewContext
}
var container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "MyApp")
// turn on persistent history tracking
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
container.newBackgroundContext()
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: {(storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
My question is, how can I debug this? I understand the fact, this is trying to access the array of Objects B, that is already released, I just don't understand why it's released. Could it be because I opened the SwiftUi window and closed it? But why doesn't the connection just keep it?
Is there a way to prevent this error? I can see 3 threds running in the debugger, when the excecption is thrown, but I'm not aware of "creating new thread" and being new to Swift, not sure how to start a one, or stop one from being created.
Apart from passing the context down directly to the view, in two places I use a helper that looks like this:
public func getManagedContext() -> NSManagedObjectContext {
return (NSApplication.shared.delegate as! AppDelegate).coreDataStack.context
}
Upvotes: 0
Views: 102
Reputation: 26
You can try fetching values in DipatchQueue.main block it will avoid blocking the current thread.
Upvotes: 1