I am at a dead end and could not track any textbook or document on how best to do this.
Problem: I have two objects: Person and Location. A person can have many places. Everything is set up correctly for me and you can add / remove people from the table without any problems.
The problem I am facing is trying to add and remove a location after creating the first - when the person is inserted the first time, it also adds the location.
For this purpose, the PersonModel (Person Entity) class has:
class PersonModel: NSManagedObject { @NSManaged var Name: String @NSManaged var Age: String @NSManaged var Location: NSOrderedSet }
The LocationModel (Location Entity) class has:
class LocationModel: NSManagedObject { @NSManaged var State: String @NSManaged var Person: PersonModel }
What is the best way to access and delete items in a Location object? Should I remove an object from PersonModel or through LocationsModel?
Do the following:
func deleteObject(rowIndex:NSIndexPath){ let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate let managedContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName:"Locations") var error: NSError? locationsArray = managedContext.executeFetchRequest(fetchRequest,error: &error)! managedContext.deleteObject(locationsArray[rowIndex.row] as NSManagedObject) var error:NSError? = nil if (!managedContext.save(&error)){ abort() } }
This does not work because it returns all locations, not just the locations of objects associated with the parent / related person. There should be an easy way to do this - perhaps with a predicate?
Can someone help me point me in the right direction?
Thanks!
UPDATE: For future people having the same task.
1) Make sure the rules for deleting relationships are correct. In my case, I wanted to be able to delete locations, but keep a Person. Delete rules should be set as follows: Location - Delete Rule: Cascade, Person - Delete Rule: Nullify
2) The final code is as follows:
func deleteTrigger(rowIndex:NSIndexPath){ var personRef: PersonModel = existingItem as PersonModel let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate let managedContext:NSManagedObjectContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName:"Locations") let predicate = NSPredicate(format: "Person == %@", personRef) fetchRequest.predicate = predicate var error: NSError? = nil locationArray = managedContext.executeFetchRequest(fetchRequest,error: &error)! managedContext.deleteObject(locationArray[rowIndex.row] as NSManagedObject) locationArray.removeAtIndex(rowIndex.row) tableview.deleteRowsAtIndexPaths([rowIndex], withRowAnimation: UITableViewRowAnimation.Fade) if (!managedContext.save(&error)){ abort() } }