Group Group Group Group Group Group Group Group Group

Crash when I use NSAsynchronousFetchRequest with 1 activated

I think I tried everything the last days, but I am stuck.

I like to use a NSAsynchronousFetchRequest and populate a tableview.
It looks as it is working, but when I enable the debug option 1. I get an error when I try to execute the fetch request. And it makes no difference if I try it on the main thread or on the private thread.

crash here -> try backgroundContext.execute(asynchronousFetchRequest)
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

here the sample code - near the same as in the book

// Creates asynchronousFetchRequest with the fetch request and the completion closure
let asynchronousFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { asynchronousFetchResult in

            // Retrieves an array of dogs from the fetch result `finalResult`
            guard let result = asynchronousFetchResult.finalResult as? [DOG] else { return }
            // Dispatches to use the data in the main queue
            DispatchQueue.main.async {
                // Do something
                // Iterates the result of the private context
                for dog in result {
                    // Retrieves the ID of the entity
                    let objectID = dog.objectID
                    // Creates a new dog entity queue-safe
                    guard let queueSafeDog = self.persistentContainer.viewContext.object(with: objectID) as? DOG else { continue }
                    // Adds to the array
        do {
                // Executes `asynchronousFetchRequest`
            let backgroundContext = persistentContainer.newBackgroundContext()
            try backgroundContext.execute(asynchronousFetchRequest)
            } catch let error {
                print("NSAsynchronousFetchRequest error: \(error)")

is this schema flag unusable with AsyncFetchRequest?


Hi @oliz, sorry this took so long to reply to. I wouldn’t dispatch to the main queue until you’re actually going to update the UI. For example, does removing everything from dogs have to be in the main queue?

When you’re iterating over result here you’re on the main queue and so accessing objectID might be an issue. I’d suggest pushing that dispatch to the main queue all the way down so that it was only wrapping the table view’s reload call. If you do that you can directly access the DOG object from your instead of having to call the object(with:) method, for example.

Have you gone into your schema in Xcode and turned on the thread sanitizer? That might help as well. One of the last chapters in the book speaks to the thread sanitizer.