-1

I've seen many posts showing how to add or remove core data objects from an NSMutableSet for a "to-many" relationship. However, how do you update an existing one? Specifically, I am displaying a table of objects from the "many" side of a one-to-many relationship in a ViewController. When the user clicks on a table row (representing one of these objects), I would like to send this particular object to another ViewController via the prepareForSegue method. I have no problems doing this with "one" side of the relationship. But I'm having trouble doing it with the "many" side of the relationship. Can you please post an example of how to send an object from the "many" side of the relationship to another ViewController, have that VC update it and save it to core data?

Thank you very much!!!!

Barb
  • 124
  • 7

2 Answers2

1

Just update the object in question itself! It could not be simpler.

NSSet *employees = department.employees;
Employee *bride = [employees lastObject];
NSLog(@"%@", bride.lastName); // "Johnson"
bride.lastName = @"Smith";
[self.managedObjectContext save:nil];

NSLog(@"%@", [department.employees.lastObject lastName]); // "Smith"
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • This works because while `NSSet` is immutable, the objects it contains do not have to be. So what is happening here is that a contained object is being modified, but the set still contains the same object, so you are not breaking mutabliity – Abizern Jan 27 '13 at 11:18
1

If you have a relationship and query it, you get back a set.

If you want to change this set, rather than change the objects contained in the set, you can use a handy method:

For example

NSMutableSet *relatedObjects = [object mutableSetValueForKey:@"relationshipName"];
[relatedObjects addObject:anotherRelatedObject];

This way - you get back a mutable set of related objects rather than just the immutable set, and any changes you make will be persisted on a save.

Abizern
  • 146,289
  • 39
  • 203
  • 257