How to correctly setup a NSPredicate for a to-many relationship when using Core Data?

后端 未结 2 1854
借酒劲吻你
借酒劲吻你 2020-12-02 09:15

I have a Core Data model in which a Task entity includes an optional to-many relationship ExcludedDays to the ExcludedDay entity. One of the properties of ExcludedDay is day

2条回答
  •  时光取名叫无心
    2020-12-02 10:01

    Quite curious how to solve this I setup a little project and created the context you are using.

    NSDate *today = [NSDate date];
    NSMutableArray *objects = [NSMutableArray array];
    
    {
        NSArray *day = [NSArray arrayWithObjects:today, [today dateByAddingTimeInterval:20.0f], nil];
        NSDictionary *excludedDay = [NSDictionary dictionaryWithObject:day forKey:@"day"];
        NSDictionary *object = [NSDictionary dictionaryWithObject:excludedDay forKey:@"excludedDay"];
    
        [objects addObject:object];
    }
    
    {
        NSArray *day = [NSArray arrayWithObjects:[today dateByAddingTimeInterval:20.0f], nil];
        NSDictionary *excludedDay = [NSDictionary dictionaryWithObject:day forKey:@"day"];
        NSDictionary *object = [NSDictionary dictionaryWithObject:excludedDay forKey:@"excludedDay"];
    
        [objects addObject:object];
    }
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NONE excludedDay.day == %@", today];
    NSArray *filtered = [objects filteredArrayUsingPredicate:predicate];
    
    NSLog(@"%@", filtered);
    

    This gives the object when:

    1. The day array is empty
    2. The day array does not contain the 'today' date

    This does not give the object when:

    1. The day array contains the 'today'
      • It doesn't matter how many objects in the day array are

提交回复
热议问题