目前我有一个解决方案,但不是一个干净的解决方案:
我想以有序的关系按 20 组无故障地批处理。
因此,每次我处理一个索引除以 20(索引 % 20 == 0)的索引时,我都会为接下来的 20 使用一个新的 NSFetchRequest 并通过调用一个通用字段名称来消除它们的错误。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row % 20 == 0) {
NSArray *objectsToUnfault = [[someObject.orderedRelationship array] subarrayWithRange:NSMakeRange(indexPath.row, MIN(20, [someObject.orderedRelationship count] - indexPath.row))];
// It's important to hold on this array, otherwise objects fault back
self.lastPrefetch = [self preFetchEntityOfClass:[Post class] faultObjects:objectsToUnfault error:&error];
}
//... continue and create cell
}
- (NSArray *)preFetchEntityOfClass:(Class)entityClass faultObjects:(NSArray*)objects error:(NSError **)error {
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:NSStringFromClass(entityClass) inManagedObjectContext:self.managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF in %@", objects];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setPredicate:predicate];
[request setFetchBatchSize:MIN([objects count], 20)];
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:error];
// I assume all my objects has this field "uid"
NSArray *resultsUid = [results valueForKey:@"uid"]; //Batch unfaulting (results is a BatchFaultArray, private class type)
if ([resultsUid count] != [results count]) {
NSLog(@"Error: wrong count of uids"); //We need to use resultsUid, to avoid compiler opt
}
return results;
}