关于Core Data的一些整理(四)
- 调用Core Data文件中的Request模板进行条件匹配
1 //获取ObjectModel相当于获取Core Date文件 2 NSManagedObjectModel *model = self.coreDataStack.contenxt.persistentStoreCoordinator.managedObjectModel; 3 self.fetchRequest = [model fetchRequestTemplateForName:@"FetchRequest"]; 4 self.venues = [self.coreDataStack.contenxt executeFetchRequest:self.fetchRequest error:nil];
- iOS8新增Asynchronous异步调用Core Data,提高性能
1 @property (nonatomic, strong) NSFetchRequest *fetchRequest; 2 @property (nonatomic, strong) NSAsynchronousFetchRequest *asyncFetchRequest; 3 4 //asyncFetch只是对普通request的封装 5 self.fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Venue"]; 6 self.asyncFetchRequest = [[NSAsynchronousFetchRequest alloc] initWithFetchRequest:self.fetchRequest completionBlock:^(NSAsynchronousFetchResult * _Nonnull result) { 7 self.venues = result.finalResult; 8 [self.tableView reloadData]; 9 }]; 10 //注意调用的是executeRequest:方法 11 [self.coreDataStack.contenxt executeRequest:self.asyncFetchRequest error:nil];
- iOS8新增批(Batch)处理,链接
Batch Updates或Batch Deletes与普通NSFetchRequest
请求不同的是,他们都基于NSPersistentStoreRequest
类,这是直接对底层的NSPersistentStore
进行数据操作的请求,而不经过NSManagedObjectContext
,因此避免将固态存储的数据转移到内存再处理的过程,因此效率大大提升。
1 //设置批处理请求,包含更新的内容,影响的stores 2 NSBatchUpdateRequest *batchUpdate = [NSBatchUpdateRequest batchUpdateRequestWithEntityName:@"Venue"]; 3 batchUpdate.propertiesToUpdate = @{@"favorite":@YES}; 4 batchUpdate.affectedStores = self.coreDataStack.contenxt.persistentStoreCoordinator.persistentStores; 5 batchUpdate.resultType = NSUpdatedObjectsCountResultType;//返回更新的行数 6 7 NSBatchUpdateResult *batchResult = [self.coreDataStack.contenxt executeRequest:batchUpdate error:nil]; 8 NSLog(@"%@", batchResult.result); 9 //在iOS9中又新增