如何使用NSpredicate进行查询

时间:2013-05-08 06:49:13

标签: nspredicate

我是xcode和核心数据的新手。我想使用核心数据执行以下查询。

从roomtable中选择count(roomtype),其中roomtype = @“ac single”和roomstatus = @“YES”;

请指导我如何使用NSPredicate来执行查询。

1 个答案:

答案 0 :(得分:1)

处理核心数据的步骤如下:

创建一个获取请求以将对象拉入托管对象上下文

// Assuming you have an entity called Rooms:
[NSFetchRequest fetchRequestWithEntityName:@"Rooms"];

现在创建要应用于该实体的谓词以过滤返回的内容

// Assuming that the Rooms entity has attributes for "roomType" and "roomStatus"
// I'd actually use %K and attributes - but this will do until you learn about them.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomType == %@ and roomStatus == %@", @"ac single", @"YES"];

[request setPredicate:predicate];

运行获取请求

// Assuming you have the managed Object Context in a property
NSError *error;
NSArray *results = [self.moc executeFetchRequest:request error:&error];

// Make sure the results are not nil, if they are handle the error
if (!results) {
    // Handle error in here using the error parameter you passed in by reference.
}

结果现在在一个数组中,您只需使用以下内容即可获得满足谓词的实体数:

NSUInteger resultCount = [results count];

使用Core Data时,这是所有标准内容。如果你通过它并尝试理解这些步骤 - 那么编写自己的获取请求将会很长。