我正在尝试以一定大小(batchSize)的块处理大量对象。这个循环似乎有效,但它只处理了一半的记录。相关的代码是:
{
//Prepare fetching products without images in the database
NSFetchRequest * productFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Product"];
//Sort by last changed photo first
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"photoModificationDate" ascending:NO];
[productFetchRequest setSortDescriptors:@[sortDescriptor]];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateString];
[productFetchRequest setPredicate:predicate];
//First get the total count
NSUInteger numberOfProducts = [self.backgroundMOC countForFetchRequest: productFetchRequest error: &error];
NSLog(@"Getting images for: %d products", numberOfProducts);
//Then set the batchsize to get chunks of data
NSUInteger batchSize = 25;
[productFetchRequest setFetchBatchSize: batchSize];
[productFetchRequest setFetchLimit:batchSize];
//Fetch the products in batches
for (NSUInteger offset = 0; offset < numberOfProducts; offset += batchSize) {
@autoreleasepool {
[productFetchRequest setFetchOffset: offset];
NSArray * products = [self.backgroundMOC executeFetchRequest:productFetchRequest error:&error];
NSLog(@"Offset: %d, number of products: %d", offset, [products count]);
if (!products) {
return NO;
}
for (Product * product in products) {
NSLog(@"Downloading photo for product: %@", product.number);
[self downLoadAndStoreImageForProduct:product];
}
[self saveAndResetBackgroundMOC];
}
}
return YES;
}
日志显示,对于计数的前半部分 (numberOfProducts),它按预期工作。因此处理了 25 种产品的块。在前半部分之后,循环中的 fetchrequest 结果有 0 条记录。如果我再次重试相同的代码,则再次只处理一半(剩余)记录,因此总共 3/4。我究竟做错了什么?注意,managedObjectContext 不仅保存了,保存后还会重置,以节省内存。如果我不分块执行此操作,则程序在下载大约 3000 张图片后会持续崩溃。