iphone - 使用 NSPredicate 获取核心数据对象数组?

标签 iphone objective-c core-data ios nspredicate

假设我有一个名为 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/

相关文章:

ios - 格式指定类型 'int' 但参数的类型为 'UIViewContentMode'

ios - 如何将更改从一个 ManagedObject 写入类似的 ManagedObjects

ios - 核心数据中的 True/False bool 值

ios - 在订购应用程序中设置核心数据关系

iphone - 如何在 MKMapView (SDK3.2) 中使用 UIPopoverController 在 iPad 上关闭 PopoverAnimated

ios - 动画 barTintColor 推送 segue

iphone - 从两个分组的 UITableView 单元格中删除内部分隔符

ios - 从 customCell 按钮调用 TableView.m 中的操作

ios - 同一部 iPhone 中的多个 MDM 配置文件

objective-c - NSColor 及其色调分量