ios – UI在执行NSBatchDeleteRequest时冻结

NSFetchRequest *request = [Report fetchRequest];
request.predicate = [NSPredicate predicateWithFormat: @"reportId IN %@",self.selectedRowsInEditMode];

NSBatchDeleteRequest *deleteDetailsRequest = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
deleteDetailsRequest.resultType = NSBatchDeleteResultTypeStatusOnly;
[self.managedObjectContext executeRequest:deleteDetailsRequest error:&errorExecuteRequest];

if (!errorExecuteRequest) {
    NSError *deleteSaveError;
    BOOL saveSuccessful = [self.managedObjectContext save:&deleteSaveError];
    [self.tableView removeLoadingActivityView];

这是我尝试一次删除多个报表管理对象的代码,但是当调用executeRequest时,UI会冻结很长一段时间然后删除.但就删除而言,NSBatchDeleteRequest应该非常快.我尝试了多次修改以使其正常工作但没有成功.
我不确定我在这里做错了什么.所以任何人都可以建议让它在没有UI故障的情况下工作.

最佳答案 希望对您有所帮助!

我最后添加了以下内容,以便在批量删除后处理上下文.

[self.managedObjectContext refreshAllObjects];

// Initialize Fetch Request
NSFetchRequest *fetchRequest = [Report fetchRequest];

// Add Sort Descriptors
fetchRequest.predicate = [NSPredicate predicateWithFormat: @"reportId IN %@",self.selectedRowsInEditMode];

// Initialize Asynchronous Fetch Request
NSAsynchronousFetchRequest *asynchronousFetchRequest = [[NSAsynchronousFetchRequest alloc] initWithFetchRequest:fetchRequest completionBlock:^(NSAsynchronousFetchResult *result) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // Process Asynchronous Fetch Result
        [weakSelf processAsynchronousFetchResult:result];
    });
}];

// Execute Asynchronous Fetch Request
[self.managedObjectContext performBlock:^{
    // Execute Asynchronous Fetch Request
    NSError *asynchronousFetchRequestError = nil;
    NSAsynchronousFetchResult *asynchronousFetchResult = (NSAsynchronousFetchResult *)[weakSelf.managedObjectContext executeRequest:asynchronousFetchRequest error:&asynchronousFetchRequestError];

    if (asynchronousFetchRequestError) {
        NSLog(@"Unable to execute asynchronous fetch result.");
        NSLog(@"%@, %@", asynchronousFetchRequestError, asynchronousFetchRequestError.localizedDescription);
    }
}];

或者在下面使用全局队列来运行后台和主队列以更新UI

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});
点赞