gpt4 book ai didi

ios - CoreData 有序关系 - 使用 NSFetchRequest 进行批处理

转载 作者:可可西里 更新时间:2023-11-01 03:32:26 25 4
gpt4 key购买 nike

背景 - 批量无故障:
NSFetchRequest 允许批处理 unfault - 例如,使用 1000 个结果的查询,它会把所有结果都作为错误,然后它会一次 unfault X 个对象(即索引 0-20,然后是 21-40,等等)

当在 NSFetchResultsController 中用于 UITableViewDataSource 时,这种行为非常好,它允许快速 UI 滚动,因为它不会一个接一个地显示对象。

现在我的问题是:
我正在为对象列表使用有序关系,比方说帖子

由于 Post 可能出现在我的模型的很多列表中,我无法将其索引存储在 Post 实体的每个列表中并将其用作参数用于排序结果。

至于目前我还没有找到NSFetchRequest按照这个顺序去fetch的方法,所以不能用它的batch unfaulting。因此,我正在解决与索引的关系,最终我一个一个地确定无误,这会导致滚动颠簸。

NSFetchResultsController有什么办法可以按照顺序关系去取吗?或者,是否有非私有(private)的批量无故障 API?

最佳答案

目前我有一个解决方案,但不是一个干净的解决方案:
我想按顺序关系按 20 人为一组进行无故障批处理。

因此,每次我寻址一个索引,它的索引除以 20(索引 % 20 == 0),我为接下来的 20 个使用一个新的 NSFetchRequest,并通过调用一个公共(public)字段名称来避免它们出错。

- (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;
}

关于ios - CoreData 有序关系 - 使用 NSFetchRequest 进行批处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com