Search code examples
cocoacore-datatagsnsarraycontroller

Adding to to-many / many-to-many core data relationship


I have 2 Entities, related by a many-to-many relationship.

Thing<<->>Tag

There is one NSArrayController controlling the entity "Tag", bound to the managedObjectContext. By the array controllers add: and remove: action i can add instances of tag to the collection.

There is a second NSArrayController controlling "Thing" entities, also bound to the managedObjectContext.

So each of the controllers manages all instances of their entity.

Now, let's say there are 5 "tag" and 3 "thing" instances already created by their array controllers.
I'd like to link individual tags to a thing. I just want to create the relationship between an existing thing to an existing tag instance.

  • Is addObject: of NSArrayController the right method for that? Or does it create a new managedObject?

  • Would it be equivalent to:

    NSMutableSet *tags = [aThing mutableSetValueForKey:@"tags"];
    [tags addObject:existingTag];
    

    ?

  • Is there some best practice for a tagging system?

Solution

  • I've found it helpful (in the latest version of Xcode) to select the entity in the core data modeller, and then go to the file menu, and select new file -> Core Data -> NSManagedObject subclass. It automatically creates a class with the necessary members AND ALSO methods for adding objects in the toMany relationships.

    If you've done that, then you just need to get ahold of the thing instance to which you want to add a tag and you can call the method declared for you to do so. How that method is named is obvious from the header file generated.