【问题标题】:NSPredicate nested dictionary dynamic keyNSPredicate 嵌套字典动态键
【发布时间】:2015-04-15 09:52:05
【问题描述】:

我正在使用核心数据来获取对象列表。这些对象有一个名为“类别”的属性。这个 category 属性是一个 NSDictionary,由 json 构造而成:

@{@"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]];

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

编辑:

为了澄清我会使用

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

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

【问题讨论】:

    标签: ios objective-c core-data nsdictionary nspredicate


    【解决方案1】:

    如果我理解正确,categories 是您实体上的字符串属性,其中包含 JSON 数据,您的托管对象会解析此 JSON,以便将其作为字典读取。

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

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

    【讨论】:

    • Core Data 不能原生存储 NSDictionary 对象,只能存储字符串和数字等简单数据类型。我的印象是您刚刚开始学习 Core Data,当您更好地理解它时,也许应该回到这个问题。
    【解决方案2】:

    试试这个

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

    【讨论】:

    • 抱歉,检索到的总是空数组
    • 做了更改,请检查
    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2021-05-10
    相关资源
    最近更新 更多