Core Data predicate : unimplemented SQL generation for predicate

前端 未结 5 1445
旧巷少年郎
旧巷少年郎 2020-12-09 10:50

Basically I got 3 entities in my data model : Brand, Model and Trim.

  • A brand has a one-to-many relationship with Model called \"models\". (one brand have multi
相关标签:
5条回答
  • 2020-12-09 11:05

    "ANY" in a Core Data predicate works only for a single to-many relationship. Since your query involves two to-many relationships, you have to use a SUBQUERY:

    [NSPredicate predicateWithFormat:@"SUBQUERY(models, $m, ANY $m.trims IN %@).@count > 0",
        arrayOfTrims];
    
    0 讨论(0)
  • 2020-12-09 11:15

    When you use a predicate in a CoreData operation, the predicate gets translated into SQL. That translation is not possible for all NSPredicate operations, you've hit one that isn't. My suggestion would be something along the lines of:

    NSMutableArray* predicates = [NSMutableArray new];
    for(NSString* trim in arrayOfTrims)
    {
        [predicates addObject:[NSPredicate predicateWithFormat:@"%@ IN models.trims", trim]];
    }
    NSPredicate*    predicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
    
    0 讨论(0)
  • 2020-12-09 11:22

    In my case I got this error because I made a silly mistake and didn't have the argument in the right data type.

    I was trying to do:

    let firstPredicate = NSPredicate(format: "firstName BEGINSWITH[cd] %@", firstNameField.stringValue)

    and forgot to put the ".stringValue."

    0 讨论(0)
  • 2020-12-09 11:25

    The keyword IN can be used but you cannot apply ANY at the same time as that does not make sense when you turn it into SQL.

    The predicate you are most likely looking for is:

    [NSPredicate predicateWithFormat:@"models.trims IN %@", arrayOfTrims];
    

    But that isn't going to work in this case either because you are going across a relationship. So what you need to do is reverse the whole thing:

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Model"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"trims in %@", arrayOfTrims]];
    
    NSError *error = nil;
    NSArray *modelArray = [moc executeFetchRequest:request error:&error];
    if (!modelArray) {
      NSLog(@"Error: %@\n%@", [error localizedDescription], [error userInfo]);
    }
    NSArray parentObjectArray = [modelArray valueForKey:@"${PARENT_RELATIONSHIP_NAME}"];
    

    Basically you are fetching the child objects to satisfy your ANY and then using KVC to retrieve the parent objects that you care about.

    0 讨论(0)
  • 2020-12-09 11:32

    This exception is also raised if one of the predicates uses a column (i.e. field) name that does not exist. Totally misleading error message...

    0 讨论(0)
提交回复
热议问题