这是我的获取请求的定义,我使用score属性进行排序:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:[Product entityName]];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:ProductAttributes.score ascending:YES];
[fetchRequest setSortDescriptors:@[ sortDescriptor ]];
我使用它来定义我的异步提取:
NSAsynchronousFetchRequest *asynchronousFetchRequest = [[NSAsynchronousFetchRequest alloc] initWithFetchRequest:fetchRequest completionBlock:^(NSAsynchronousFetchResult *result) {
dispatch_async(dispatch_get_main_queue(), ^{
// Process Asynchronous Fetch Result
[weakSelf processAsynchronousFetchResult:result];
});
}];
和perfenter代码在manged对象上下文中提取:
// Execute Asynchronous Fetch Request
[moc performBlock:^{
// Execute Asynchronous Fetch Request
NSError *asynchronousFetchRequestError = nil;
NSAsynchronousFetchResult *asynchronousFetchResult = (NSAsynchronousFetchResult *)[moc executeRequest:asynchronousFetchRequest error:&asynchronousFetchRequestError];
if (asynchronousFetchRequestError) {
NSLog(@"Unable to execute asynchronous fetch result.");
NSLog(@"%@, %@", asynchronousFetchRequestError, asynchronousFetchRequestError.localizedDescription);
}
}];
我把它放在我的完成功能中,它大部分时间都失败了。排序有效但有时它在集合中被1或2关闭。假设n项的得分从0到n:
- (void)processAsynchronousFetchResult:(NSAsynchronousFetchResult *)asynchronousFetchResult {
if (asynchronousFetchResult.finalResult) {
[_items addObjectsFromArray:asynchronousFetchResult.finalResult];
for(int i=0 ; i<_items.count ; i++) {
Product *product = _items[i];
assert([product.score intValue]==i);
}
}
}
与普通获取结果相同的控制器可以很好地进行排序。任何想法为什么异步提取打破了排序,并有一种方法来强制执行。