2016-06-07 33 views
0

在PHP中,我會使用array_chunk來拆分數組,然後處理每個塊。在目標C中,這看起來並不那麼簡單,有沒有比這個更清潔的方式?批處理一個NSArray

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

回答

1

如果// 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 
}