【问题标题】:Subquery IN statement collection子查询 IN 语句集合
【发布时间】:2016-08-11 04:21:56
【问题描述】:
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 

我有这个错误。 sectionNames 是 section 对象的名称数组。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SUBQUERY(sections, $section,  $section.name IN (
)).@count > 0"'

【问题讨论】:

    标签: objective-c realm


    【解决方案1】:

    您应该使用NSPredicate 的参数替换支持,而不是通过+[NSString stringWithFormat:] 使用NSString 的字符串插值:

    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 的参数替换将 object 替换到谓词中,而无需担心字符串表示是否与 NSPredicate 期望的匹配。

    【讨论】:

    • 它有效,感谢您的回答。但我认为有些不对劲。在我的部分数组列表中有 3 个子部门。 2个子部门属于“A部门”,1个子部门属于“B部门”。但在经过过滤的部门数组之后,它只返回“一个部门”。我如何追踪这个错误?
    • 没有更多信息很难说。我建议发布一个包含更多详细信息的新问题,以便人们可以帮助您。
    • stackoverflow.com/questions/38890556/…我又问了一遍。请帮我检查。怎么了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多