CoreData 查询数据
1. NSFetchRequest
resultType
- NSManagedObjectResultType
- NSCountResultType
- NSDictionaryResultType
- NSManagedObjectIDResultType
其中默认属性为NSManagedObjectResultType
NSManagedObjectResultType
NSManagedObjectResultType
是NSFetchRequest 的默认属性,执行查询后,数组里每个元素,就是NSFetchRequest 对应的NSManagedObject对象。
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Doge"];
//默认就为NSManagedObjectResultType
//fetchRequest.resultType = NSManagedObjectResultType;
NSArray *result = [_context executeFetchRequest:fetchRequest error:nil];
//这里数组的元素为Doge对象
NSCountResultType
NSCountResultType
执行查询后,返回的数组,包含一个对象,NSNmber.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Doge"];
fetchRequest.resultType = NSCountResultType;
NSArray *result = [_context executeFetchRequest:fetchRequest error:nil];
//这里数组的元素为 NSNumber ,一般数组只有一个元素
if ([result count] > 0){
NSInteger count = [[results objectAtIndex:0] integerValue];
}
NSDictionaryResultType
NSDictionaryResultType
顾名思义,是返回一个字典,除了设置fetchRequest.resultType
,还需要设置fetchRequest.propertiesToFetch
NSManagedObjectIDResultType
返回唯一标识
Prior to iOS 5, fetching by ID was popular because NSManagedObjectID is thread-safe and using it helped developers implement the thread confinement concurrency model. Now that thread confinement has been deprecated in favor of more modern concurrency models, there’s little reason to fetch by object ID anymore.
2. NSPredicate
The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.
NSFetchRequest 支持使用谓词来作为,查询筛选条件
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Doge"];
fetchRequestWithEntityName:@"Doge"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"age > 5"];
NSArray *result = [_context executeFetchRequest:fetchRequest error:nil];
3. NSSortDescriptor
除了使用支持使用谓词,NSFetchRequest 还支持使用NSSortDescriptor
进行排序
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Doge"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptor];
NSArray *result = [_context executeFetchRequest:fetchRequest error:nil];
4. NSAsynchronousFetchRequest
NSFetchRequest 是同步查询的,CoreData 也提供了异步查询的类NSAsynchronousFetchRequest
,它通过一个 block ,将数据异步返回,注意,查询方法使用的是 -executeRequest:error:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Doge"];
NSAsynchronousFetchRequest *asyncFetchRequest = [[NSAsynchronousFetchRequest alloc] initWithFetchRequest:fetchRequest completionBlock:^(NSAsynchronousFetchResult * _Nonnull results) {
NSLog(@"%@",results);
}];
[_context executeRequest:asyncFetchRequest error:nil];