假设我有一个名为 Person 的核心数据实体。我如何获得属性匹配特定值的 Persons 的 NSArray?例如特定年龄、高度或体重的人……或者高度、体重和年龄为特定值的人……
我可以像这样使用 NSPredicate 吗:
NSPredicate *pred =
[NSPredicate predicateWithFormat:
@"(age == 25) OR (height_in_cms == 185) OR (age == 30 AND height_in_cms == 170 AND weight_in_kgs == 80)";
// All properties are NSNumber
最佳答案
我不是 predicateWithFormat:
的语法专家,但您掌握了基本要点。您可以在 Apple 的 Predicate Programming Guide 中找到有关格式的详细信息。 .如果您在询问如何处理谓词,这里有一个片段向您展示了步骤:
// Create a fetch request.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Set the entity for the fetch request.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[entity release];
// Set the predicate for the fetch request.
[fetchRequest setPredicate:predicate];
// Perform the fetch.
NSError *error;
NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
如果您希望对结果进行排序,您可以在执行提取之前使用 setSortDescriptors:
将排序描述符数组传递给提取请求。
关于iphone - 使用 NSPredicate 获取核心数据对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4252628/