2.13.2. 对结果集进行筛选(Core Data 应用程序实践指南)

时间:2021-11-06 01:18:43

  Core Data通过谓词(NSPredicate)来筛选,比如限定获取的数量等。谓词基本对存储区不敏感,但也有例外,比如:matches可用在 in-memory存储区,但是不能用在SQLite存储区。谓词是SQL里面的where子句。

  在筛选的过程中,每个托管对象都会根据谓词求值,根据返回的YES或NO取舍。

  具体的谓词规则查阅:developer.apple.com 并搜索Predicate Programming Guide。

  程序修改代码如下:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
NSPredicate *filter = [NSPredicate predicateWithFormat:@"name != %@",@"Coffee"];
[request setPredicate:filter]; [request setSortDescriptors:[NSArray arrayWithObject:sort]];
NSArray *itemObjects = [_coreDataHelper.context executeFetchRequest:request error:nil];
for (Item *item in itemObjects) {
NSLog(@"item name = %@", item.name);
}