如何使用NSPredicate捕获子对象?

7
我对Core Data还不熟悉,想用一个查询获取各种类型的所有子对象。比如说有一个"Animal"类型作为父类,"Cat"、"Dog"和"Bird"作为子类。我想在单个查询中获取猫和狗,但不包括鸟,以Animal对象的形式返回。这是否可能?
3个回答

5

1
这是一个非正式的属性,因为您可以使用KVC来访问它(因为有一个方法存在),而不是一个正式的(@property)属性。 - Peter Hosey
你实际上不能在SQLite存储中使用这种方法,因为当对象处于故障状态时,entity属性是不可用的。你别无选择,只能进行后获取过滤步骤。 - Rob Keniger

3

是的,这是可能的:

// 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) { }

谢谢您的快速回复。很抱歉,我忘了提到最重要的事情:还有一个孩子(称为“小鸟”)。我需要的是,获取猫和狗,但不包括小鸟。我已经编辑了主要问题。 - cocoapriest

0

虽然这个条件 (entity.name != "Bird") 在你只有 "Cat", "Dog" 和 "Bird" 时可能有效,但如果你以后添加了更多的 "Animals",它就不再有效。你可以使用 entity.name == "Dog" && entity.name == "Cat"

这是一个问题:“...在你的情况下,你是否会有其他动物?”

玩得开心 =)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接