如何使用 NSPredicate 捕获子对象?
-
19-09-2019 - |
题
我是核心数据的新手,并尝试通过一个查询获取各种类型的所有子对象。假设有一个“动物”类型作为父级,“猫”、“狗”和“鸟”作为子级。我想要猫和狗,但不希望在单个查询中将鸟类作为动物对象返回。是否可以?
解决方案
被管理的对象有一个 entity
财产, ,所以你应该能够结合 凯文·西尔维斯特的解决方案 和 谓词 的 entity.name != "Bird"
.
其他提示
是,它是可能的:
// 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) { }
虽然这(entity.name != "Bird"
)可以工作,如果你只有“猫”,“狗”和“鸟”,它不一样,如果以后添加更多的“动物”工作。您还可以使用entity.name == "Dog" && entity.name == "Cat"
这是一个情况下,“......你永远不会有任何其他的,你的情况,动物吗?”
有乐趣=)
不隶属于 StackOverflow