I'm trying to update a relationship in Core Data but am experiencing this issue. I have 2 entities: Trip
and GPSLocation
. A Trip
can have many GPSLocation
but a GPSLocation
can only be in one Trip
, hence an one-to-many relationship from Trip
to GPSLocation
. I set up my entities in Xcode's model editor like so:
Entity: GPSLocation
relationship: trip
destination: Trip
inverse: gps
Type: To one
Entity: Trip
relationship: gps
destination: GPSLocations
inverse: trip
Type: To many
Assuming the variable trip
is an instance of my Trip entity. In my update routine, I have:
let request = NSBatchUpdateRequest(entityName: "GPSLocations")
request.predicate = somePredicate
request.propertiesToUpdate = ["trip": trip]
request.resultType = .UpdatedObjectIDsResultType
do {
let responses = try managedContext.executeRequest(request) as! NSBatchUpdateResult
print responses.result!
} catch let error as NSError {
print(error)
}
This code is giving me an NSInvalidArgumentException Reason: 'Invalid relationship' and I'm not sure why. Any help would be very appreciated! Thank you.
EDIT: My predicate is a pretty simple one: NSPredicate(format: "SELF = %@", "1")
. I confirmed that record with pk 1 exists via a database visualizer.
EDIT 2:
So I did some further testing and noticed something interesting about the 2 routines that I wrote for creating and updating records in entities. Unlike with the update
routine, I don't get this invalid relationship problem when I use the create
routine. Here is my code for both routines:
// MARK - this routine works fine
func createRecord(entityName: String, fromKeyValue: [String:AnyObject]) -> AnyObject {
let entityDesc = NSEntityDescription.entityForName(entityName, inManagedObjectContext: managedContext)
do {
let entityType = NSClassFromString("myapp." + entityName) as! NSManagedObject.Type
let entity = entityType.init(entity: entityDesc!, insertIntoManagedObjectContext: managedContext)
for key in fromKeyValue.keys {
entity.setValue(fromKeyValue[key], forKey: key)
}
try managedContext.save()
return entity
} catch let error as NSError {
return error
}
}
// MARK - this one gives me problem..
func updateRecords(entityName: String, predicate: NSPredicate, keyValue: [String:AnyObject]) -> AnyObject {
let request = NSBatchUpdateRequest(entityName: entityName)
request.predicate = predicate
request.propertiesToUpdate = keyValue
request.resultType = .UpdatedObjectIDsResultType
do {
let responses = try managedContext.executeRequest(request) as! NSBatchUpdateResult
return responses.result!
} catch let error as NSError {
return error
}
}