NSArray *sectionNames = [NSArray arrayWithObjects: @"aa", @"bb", nil];
RLMResults<Department *> *filteredDepartments = [Department objectsWhere:
[NSString stringWithFormat:@"SUBQUERY(sections, $section, $section.name IN %@).@count > 0",[NSArray arrayWithArray:sectionNames]]];
这是部门模型。
@interface Department : RLMObject
@property NSString *name;
@property (nonatomic, strong) RLMArray<Section> *sections;
@end
我有这个错误。 sectionsNames是section对象的名称数组。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SUBQUERY(sections, $section, $section.name IN (
)).@count > 0"'
答案 0 :(得分:0)
不是通过NSString
使用+[NSString stringWithFormat:]
的字符串插值,而应使用NSPredicate
的参数替换支持:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(sections, $section, $section.name IN %@).@count > 0", sectionNames];
RLMResults<Department *> *filteredDepartments = [Department objectsWithPredicate:predicate];
由于这是一种常见的模式,Realm提供了一个包装器,负责以NSPredicate
的形式为您构建+[RLMObject objectsWhere:]
:
RLMResults<Department *> *filteredDepartments = [Department objectsWhere:@"SUBQUERY(sections, $section, $section.name IN %@).@count > 0", sectionNames];
NSString
的插值将变量的字符串表示形式插入到字符串中。数组的字符串表示形式为(aa, bb)
,即not valid in an NSPredicate
format string。使用NSPredicate
的参数替换将对象替换为谓词,而无需担心字符串表示是否与NSPredicate
期望的匹配。