批处理 NSArray

Batch process an NSArray

在 PHP 中,我会使用 array_chunk 拆分数组然后处理每个块。在 objective C 中,这似乎不是那么简单,有没有比这样更简洁的方法?

- (void)processTransaction:(NSArray *)transactions
{
    NSInteger batchCount = (transactions.count - 1) / self.batchSize + 1;

    for (NSInteger batch = 0; batch < batchCount; batch ++) {
        for (NSInteger batchIndex = 0; batchIndex < self.batchSize; batchIndex++) {
            NSInteger index = batch * self.batchSize + batchIndex;
            if (index >= transactions.count) {
                return;
            }
            Transaction *transaction = [transactions objectAtIndex:index];

            // Process
        }
        // Save
    }
    // Done
}

如果// Save不是太复杂我会做

- (void)processTransaction:(NSArray *)transactions
{
    NSInteger batchIndex = 0;
    for (Transaction *transaction in transactions) {
        // Process
        batchIndex++;
        if (batchIndex >= self.batchSize) {
            // Save
            batchIndex = 0;
        }
    }
    if (batchIndex > 0) {
        // Save
    }
    // Done
}