【问题标题】:How to use NSPredicate to catch child objects?如何使用 NSPredicate 捕获子对象?
【发布时间】:2010-03-11 00:41:10
【问题描述】:

我是核心数据的新手,我尝试通过一个查询来获取各种类型的所有子对象。假设有一个“动物”类型作为父母,“猫”、“狗”和“鸟”作为孩子。我想同时获得猫和狗,但不是作为 Animal 对象返回的单个查询中的 Birds。是否可以?

【问题讨论】:

    标签: objective-c cocoa cocoa-touch core-data nspredicate


    【解决方案1】:

    Managed objects have an entity property,因此您应该能够将Kevin Sylvestre's solutiona predicateentity.name != "Bird" 结合起来。

    【讨论】:

    • 这是一个非正式的属性,只要您可以使用 KVC 来访问它(因为那里有一个方法),而不是正式的 (@property) 属性。
    • 您实际上不能将此方法用于 SQLite 存储,因为当对象出现故障时,entity 属性不可用。您别无选择,只能执行获取后过滤步骤。
    【解决方案2】:

    是的,有可能:

    // Load delegate from application and context from delegate.
    SampleAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = delegate.managedObjectContext;
    
    // Create new request.
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    
    // Create entity description using delegate object context.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Animal" inManagedObjectContext:context];
    
    // Set entity for request.
    [request setEntity:entity];
    [request setIncludesSubentities:YES];
    
    // Load array of documents.
    NSError *error;
    NSArray *animals = [context executeFetchRequest:request error:&error];
    
    // Release request.
    [request release];
    
    // Access array.
    for (id animal in animals) { }
    

    【讨论】:

    • 感谢您的快速响应。对不起,我忘了提最重要的事情:还有一个孩子(比如“鸟”)。我需要的是,得到猫和狗,但不是鸟。我已经编辑了主要问题
    【解决方案3】:

    虽然这 (entity.name != "Bird") 在您只有“Cat”、“Dog”和“Bird”时可能会起作用,但如果您稍后添加更多“Animals”则不起作用。你也可以使用entity.name == "Dog" && entity.name == "Cat"

    这是一个案例“......你还有其他的吗,动物们?”

    玩得开心 =)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多