我正在尝试根据用户定义的类型列表获取一堆特定类型的记录...
[fetchRequest setEntity:[NSEntityDescription entityForName:@"myRecord" inManagedObjectContext:self.managedObjectContext]]; NSSet *shipTypes = [NSSet setWithObjects:[NSNumber numberWithInt:70], [NSNumber numberWithInt:71], [NSNumber numberWithInt:72], [NSNumber numberWithInt:73], [NSNumber numberWithInt:74], nil]; NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"type in %@", shipTypes]; [fetchRequest setPredicate:aPredicate]; theRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
...运行时,executeFetchRequest消息抛出异常......
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (type IN {71, 73, 70, 72, 74})'
我做错了什么,或者这真的不受支持?
我相信Alex是正确的,你必须使用NSArray,虽然显然它更好,如果在这里接受NSSet,因为顺序并不重要(尽管它可能会影响SQL的运行速度).
作为旁注,我从不在任何代码中使用+ predicateWithFormat:调用,因为它无法进行编译时的健全性或类型检查.我强烈建议使用个别课程.
在这种情况下,我会这样做:
fetchRequest.entity = [NSEntityDescription entityForName:@"myRecord" inManagedObjectContext:self.managedObjectContext]]; NSArray *shipTypes = [NSArray arrayWithObjects:[NSNumber numberWithInt:70], [NSNumber numberWithInt:71], [NSNumber numberWithInt:72], [NSNumber numberWithInt:73], [NSNumber numberWithInt:74], nil]; fetchRequest.predicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"type"] rightExpression:[NSExpression expressionForConstantValue:shipTypes] modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:0]; theRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
并不是说这会在编译时捕获到这个特定的错误,但它可能会在NSExpression级别捕获它,从而使错误更清楚.