NSPredicate 嵌套字典动态键

NSPredicate nested dictionary dynamic key

我正在使用核心数据来获取对象列表。这些对象有一个名为 'categories' 的 属性。这个类别 属性 是一个从 json 构造的 NSDictionary,例如:

@{@"A":@YES, @"B":@NO, @"C":@YES}

我想获取所有核心数据对象,对于给定的类别键,类别为真。 我试过了:

NSString *categoryKey = @"A";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories.%K == YES", categoryKey]];
// or
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.categories.%@ == YES", categoryKey]];
// or
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories[%@] == YES", categoryKey];
// Throws exception : Unsupported function expression categories["A"]
// or
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories[%K] == YES", categoryKey];
// Throws exception : Unsupported function expression categories[A]
// or
NSString *categoryKeyPath = [NSString stringWithFormat:@"categories.%@", categoryKey];
NSPredicate *p = [NSPredicate predicateWithFormat:@"%K == YES", categoryKeyPath]];

但是在执行我的提取时它总是 returns 空数组(当然我有一些带有 categories[@"A"] = YES 的对象)。 我认为问题出在嵌套的字典键路径上,但我找不到用一个谓词实现此目的的方法。

编辑:

为了澄清我会使用

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    return [[evaluatedObject.categories objectForKey:categoryKey] boolValue];
}];

但是在获取核心数据时不支持predicateWithBlock:

试试这个

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.categories LIKE \"%@\":true", categoryKey]];

如果我没理解错的话 categories 是你实体的一个字符串属性,它包含 JSON 数据,你的托管对象解析这个 JSON 所以它可以作为字典读取.

问题是在执行提取之前未创建托管对象。那时,categories 只是一个字符串,没有关键路径能够从中提取您想要的信息。您将需要获取所有对象,以便它们可以构建自己的字典,然后过滤该集合。对于大型数据集,这可能会很慢。

核心数据旨在通过显式建模数据来使用;如果你把自己的数据结构塞进一个字符串中,Core Data 帮不了你。更惯用的设计是让 Categories 实体与对象的实体具有 to-many/to-many 关系。这使得通过获取类别 A 然后遵循关系来查找类别 A 中的所有对象变得微不足道。