In my CoreData data model, there is a Note entity, and a Tag entity, they have many to many relationships, so each Note can have many Tags, and each Tag may belong to many Notes.
The tags are entered as strings separated by comma:
cat, dog, pig
then I split the string to ‘cat’, ‘dog’, ‘pig’
suppose if I have a Note with tags ‘cat’, ‘dog’, ‘pig’, and I removed ‘pig’ and added ‘bird’, at first I have a string:
“cat, dog, bird” then ‘cat’, ‘dog’, ‘bird’,
Now what should I do? Should I remove all tags for this Note and re-add all the tags? But once I removed all the tags, do other Notes that share the same tag lose those tags?
Thanks!
You’re confusing deleting an object with removing it from a relationship.
Firstly, check the delete rule on your relationship:
If the delete rule is “nullify”, then that means that you can remove objects from the relationship without deleting the object. That sounds like what you want in this case: you want to be able to remove a tag from a relationship with a specific note without affecting all other notes that use the tag.
Regarding actually amending the relationship with your new set of tags, there are two things you could do. The first way is as you mentioned, to just remove all the tags from the note and re-add them. That’s quite a good plan actually. When you’re adding the tags, of course, for each tag you need to check if it exists first, and if it does, add the existing tag to the relationship.
In pseudocode:
tagsproperty to your new set of tags.The alternative way to do it, which lets you add and remove tags one at a time from the relationship, is to call
NSMutableSet *mySet = [yourNote mutableSetValueForKey:@"tags"]. That returns you a mutable set of tag objects, and any changes you make to the set are automatically seen by Core Data. So you can remove an object from it, and then that object will no longer be in the relationship, or you can add another tag to the set, and it’ll become related to the note.At no time in any of this did we delete an object from the database. All your tags still exist, we just changed which ones are related to which notes.