How do you manage and use “Many to many” core data relationships?

后端 未结 5 1182
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 15:55

I\'m creating an app and trying to use core data, because it seems like it\'s the objective-C approved way to create a data storage system. The use case I have involves \"ma

5条回答
  •  爱一瞬间的悲伤
    2020-12-04 16:24

    If your question is "how you could do that in core data", the answer is exactly as you describe. Create a to-many relationship in each entity, and define each as the inverse of the other.

    If your question is "how could this possibly work", you might find it useful to look at the sqlite database that is created from your model to see how it sets things up. CoreData is pretty good at making it so you shouldn't care about the details, but if you insist on understanding the details there's nothing stopping you from looking at the data to see what it is doing.

    Once you have this in place, you would traverse the relationship as necessary to get the attributes you want. You can do that in code using NSManagedObject instances. For example:

    NSManagedObject *manager = // get a reference to a manager here
    NSSet *employees = [manager valueForKey:@"employees"];
    for (NSManagedObject *employee in employees) {
        NSString *employeeName = [employee valueForKey:@"name"];
        // Do whatever else you want here
    }
    

    This sample can also be simplified using direct property access rather than KVO syntax, but you get the idea.

    If you are looking to traverse this many-to-many relationship more directly as part of a fetch query, then you can do some things with predicates to get what you want. Refer to Apple's predicate programming guide for examples of what you can put in a predicate

提交回复
热议问题