CoreData Batch Insert with Extra Keys (Cocoa error 1605.)

339 Views Asked by At

I am using CoreData to insert an array of dictionaries ([[String: Any]]) representing objects into a PersistentStore. When inserting the objects, I get the error The operation couldn’t be completed. (Cocoa error 1605.). The next line printed to the console is:

Error Domain=NSCocoaErrorDomain Code=1605 "(null)" UserInfo={NSValidationErrorKey=date, NSValidationErrorObject=Bot}

I am creating the array of dictionaries from a JSON object that has more keys than the corresponding ManagedObject in CoreData. Can I use NSBatchInsertRequest with keys that aren't in the corresponding ManagedObject?

Here is the code:

let batch: [[String: Any]] = getBatch()
let request = NSBatchInsertRequest(entity: Bot.entity(), objects: batch)
let insertResult = try self?.managedObjectContext.execute(request) as? NSBatchInsertResult
let result = insertResult?.result as? Bool
print(result?.description ?? "")
1

There are 1 best solutions below

0
Jinwoo Kim On

Get entity description from persistentStoreCoordinator instead of Bot.entity(). I also experienced the same issue, and it was resolved by doing this. It seems to be a Core Data bug.

let botEntity: NSEntityDescription! = self?.managedObjectContext.persistentStoreCoordinator?.managedObjectModel.entitiesByName["Bot"]

let batch: [[String: Any]] = getBatch()
let request = NSBatchInsertRequest(entity: botEntity, objects: batch)
let insertResult = try self?.managedObjectContext.execute(request) as? NSBatchInsertResult
let result = insertResult?.result as? Bool
print(result?.description ?? "")

Also, objects (input of NSBatchInsertRequest) must not contain transient property.