我正在尝试根据用户定义的类型列表来获取某种类型的一堆记录......
[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 级别捕获它,从而更清楚地表明出了什么问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)