What is an easy way to break an NSArray with 4000+ objects in it into multiple arrays with 30 objects each?

前端 未结 3 1099
终归单人心
终归单人心 2020-11-30 06:37

What is an easy way to break an NSArray with 4000 objects in it into multiple arrays with 30 objects each?

So right now I have an NSArray *stuff where [stuff count]

相关标签:
3条回答
  • 2020-11-30 07:20

    Converted the answer of @samvermette to SWIFT 3

            var arrayOfArraySlices = [ArraySlice<CBOrder>]() // array of array slices
    
            var itemsRemaining = orderArray.count
            var j = 0
    
            while itemsRemaining > 0 {
                let range = NSRange(location: j, length: min(20, itemsRemaining));
                let arraySlice = orderArray[range.location..<range.location + range.length]
                arrayOfArraySlices.append(arraySlice)
                itemsRemaining -= range.length;
                j += range.length;
            }
    
    0 讨论(0)
  • 2020-11-30 07:23

    Off the top of my head, something like (untested):

    NSMutableArray *arrayOfArrays = [NSMutableArray array];
    
    int itemsRemaining = [stuff count];
    int j = 0;
    
    while(itemsRemaining) {
        NSRange range = NSMakeRange(j, MIN(30, itemsRemaining));
        NSArray *subarray = [stuff subarrayWithRange:range];
        [arrayOfArrays addObject:subarray];
        itemsRemaining-=range.length;
        j+=range.length;
    }
    

    The MIN(30, i) takes care of that last array that won't necessarily have 30 items in it.

    0 讨论(0)
  • 2020-11-30 07:31
                NSMutableArray *arrayOfArrays = [NSMutableArray array];
                int batchSize = 30;
    
                for(int j = 0; j < [stuff count]; j += batchSize) {
    
                    NSArray *subarray = [stuff subarrayWithRange:NSMakeRange(j, MIN(batchSize, [stuff count] - j))];
                    [arrayOfArrays addObject:subarray];
                }
    
    0 讨论(0)
提交回复
热议问题