【问题标题】:NSPredicate search for child entity instance based on property of parent entityNSPredicate 根据父实体的属性搜索子实体实例
【发布时间】:2012-07-09 02:18:31
【问题描述】:

我正在尝试根据字段“guid”搜索子实体。 guid 字段在父实体中定义。我想找到 guid 等于我传入的某个值的子实例,但它总是返回 0 值的结果。我假设核心数据没有看到 guid 属性,因为它在父实体中定义。

这是我的谓词:

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:[NSEntityDescription entityForName:CHILD_ENTITY inManagedObjectContext:managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(guid like '%@')", guid]];

NSError *error = nil;

NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];

if (results != nil && results.count > 0)
    return YES;
else 
    return NO;

我的谓词格式错误吗?

【问题讨论】:

    标签: objective-c core-data ios5 nspredicate


    【解决方案1】:

    解决方案是使用属性的完整密钥路径。

    [NSPredicate predicateWithFormat:@"parent.guid like %@", guid]
    

    也就是说,如果 parent 是指向您所说的逻辑父级的属性的名称。

    当然,如果你的父母是指字面继承(即 [child isKindOfClass:[parent class]] 是 YES),那么问题可能只是引号。我假设您的意思是一个逻辑父级,它是一个不同的实例,并且与子级有关系(我猜这是 OOP 术语 VS ORM 术语,或类似的东西)。

    此外,在谓词中不需要括号或引用 %@ 就这么简单。

    【讨论】:

    • 谢谢!!!!!!通过继承,我的意思是孩子是一种父类。所以引号是问题所在。为什么引号会把它扔掉?
    • 因为框架试图为你处理好它们,所以它可能会加倍:-)
    • 啊,我明白了。非常感谢!
    猜你喜欢
    • 2019-08-15
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多