在 for 循环中进行批处理的最佳方法是什么?今天所有的 api 都有最大数量的可以获取的项目。例如,一批 100 条推文。在这种情况下,如果我有一个包含 1001 个 ID 的列表,我想查询其信息,那么我需要进行 11 次调用,每次调用 100 次。一旦形成了 100 个批次,我将使用带有条件的 for 循环在主体中调用任务。有一个更好的方法吗?考虑到这是一种常见的模式,难道不应该有一个内置的语言结构来处理这个问题吗?我错过了什么吗?
问问题
403 次
4 回答
1
在 Objective-C 中,如果需要,您可以构建自己的额外构造:
@interface NSArray (OKBatchedSubarrays)
// this will return an array of subarrays, with each of those
// containing no more items than batchSize, and the order of input
// objects being preserved
- (NSArray *)subarraysWithBatchSize:(NSUInteger)batchSize;
@end
...
@implementation NSArray (OKBatchedSubarrays)
- (NSArray *)subarraysWithBatchSize:(NSUInteger)batchSize
{
NSMutableArray *outputBatches = [NSMutableArray array];
// or arrayWithCapacity:([self count] + (batchSize - 1)) / batchSize
// if you want to be really explicit, but it's not important to the example
NSRange subarrayRange = NSMakeRange(0, batchSize);
while(subarrayRange.location < self.count)
{
// make sure we're not about to ask for out-of-bounds data
if(subarrayRange.location + subarrayRange.length > self.count)
subarrayRange.length = self.count - subarrayRange.location;
// add another batch to the output array
[outputBatches addObject:[self subarrayWithRange:subarrayRange]];
// advance beyond the range we just grabbed
subarrayRange.location += subarrayRange.length;
}
return outputBatches;
}
@end
然后在其他地方你只需要做:
NSArray *thingsToFetch = <... whatever ...>;
for(NSArray *batch in [thingsToFetch subarraysWithBatchSize:100])
{
// post to server with all things in 'batch'
}
于 2013-10-11T23:53:50.580 回答
0
我会结合一段时间和 for 循环
int totalItems = 1001;
int batchSize = 100;
int i = 0;
while ( i < totalItems ){
[self fetchABatch:(totalItems-i)];
i += batchSize;
}
-(void)fetchABatch:(int) count
{
if ( count > batchSize ){
// fetch full batch
}else{
batchSize = count;
// fetch a partial batch
}
}
于 2013-10-11T23:32:59.430 回答
0
如果 API 一次将您限制为 100 条记录,那么是的,您将需要发出 11 个请求,这是无法避免的。
我可能会创建一个NSOperation
封装每个页面的请求,为您需要的所有页面(在本例中为 11 个)创建一个,然后将它们放入一个NSOperationQueue
,当每个操作完成时,您可以将它们的结果放入一个合并数组中在内存中,或者将它们写入核心数据。
于 2013-10-11T23:34:37.390 回答
0
你的问题不清楚。但是如果你想每 100 次在 for 循环中做一些事情,就做 if(i%100==0){ //do my thing }
于 2013-10-11T23:37:50.410 回答