I'm using a batch insert request like this:
let insertRequest = NSBatchInsertRequest(entity: EntryObject.entity(), managedObjectHandler: { object in
guard index < total else { return true }
if let entryObject = object as? EntryObject {
let entry = entries[index]
entryObject.setValues(entry: entry, shouldAttemptFetchExistingTags: true)
}
index += 1
return false
})
try context.execute(insertRequest)
Each EntryObject
needs to be related to several other entities. However, NSBatchInsertRequest
doesn't allow creating relationships. Each object is saved directly to the store without loading it into a context.
So my plan is to fetch each of these objects afterwards and apply the necessary relationships.
I'm using a batch insert request because EntryObject
can contain several movies that are expensive as crap to create, and I'm continually getting super hard to trace crashes.
However when I go back to fetch these objects.. they don't exist.
I tried storing the objectIDs in a temporary array. That threw the same error. Then I tried manually merging the changes into the context I performed the batch insert on, in addition to the viewContext.
insertRequest.resultType = NSBatchInsertRequestResultType.objectIDs
let result = try context.execute(insertRequest) as! NSBatchInsertResult
if let objectIDs = result.result as? [NSManagedObjectID], !objectIDs.isEmpty {
let save = [NSInsertedObjectsKey: objectIDs]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: save, into: [PersistenceController.viewContext, context])
}
And when that didn't work, I watch the 2018 best practices for CoreData and got this going..
try context.performAndWait {
let request = NSPersistentHistoryChangeRequest ()
request.resultType = .transactionsAndChanges
let result = try context.execute (request) as! NSPersistentHistoryResult
let transactions = result.result as! Array<NSPersistentHistoryTransaction>
for transaction in transactions {
context.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
}
}
try context.save()
It's supposed to merge all the changes to the store into the main context.
However when I go back to fetch these objects, on either context.. they don't exist. Not until I kill the app and start over.
I've been trying to figure out how to completely reinit a store.. but have had no success.
How do I fetch these objects right after I create them using an NSBatchInsertRequest
?