Search code examples
iosobjective-ccore-dataentity-relationship

Core Data entity with set


I have a core data entity that contains many fields. One of them should contain a list of predefined colors. Later I would like to be able to apply a predicate on one or more of these color (like : find an object that have black and green color). My colors list'll be static.

How can I design my entity ? Should I have a Color entity with relationship ?


Solution

  • Yes, I would recommend to create a Color entity and a to-many relationship colors from your Entity to Color.

    If it is a static list of pre-defined colors, you can create the color entities when the persistent store is created. Alternatively, you can "find or create" the color entities at application startup.

    If the Color entity has a name attribute, you can find objects having a color with

    [NSPredicate predicateWithFormat:@"ANY colors.name = %@", @"red"];
    

    To check for two colors, you can either use

    [NSPredicate predicateWithFormat:@"(ANY colors.name = %@) AND (ANY colors.name = %@)", @"black", @"green"];
    

    or (I do hope that this is correct :-):

    NSArray *colorNames = @[@"black", @"green"];
    [NSPredicate predicateWithFormat:@"SUBQUERY(colors, $c, $c.name IN %@).@count >= 2", colorNames];
    

    You can also (if required) add an UIColor color attribute to the Color entry, various strategies are described in "Non-standard Persistent Attributes" in the Core Data Programming Guide.