How to split an NSArray into two equal pieces?

前端 未结 3 590
忘了有多久
忘了有多久 2020-12-06 10:33

I have an NSArray, and I want to split it into two equal pieces (if odd \"count\" then add to the latter new array) - I want to split it \"down the middle\" so to speak.

相关标签:
3条回答
  • 2020-12-06 10:47

    You also have the option of using -subarrayWithRange: detailed in the NSArray documentation:

    NSArray *firstHalfOfArray;
    NSArray *secondHalfOfArray;
    NSRange someRange;
    
    someRange.location = 0;
    someRange.length = [wholeArray count] / 2;
    
    firstHalfOfArray = [wholeArray subarrayWithRange:someRange];
    
    someRange.location = someRange.length;
    someRange.length = [wholeArray count] - someRange.length;
    
    secondHalfOfArray = [wholeArray subarrayWithRange:someRange];
    

    This method returns new, autorelease-d arrays.

    0 讨论(0)
  • 2020-12-06 10:58

    If you want an extra object on first array (in case total items are odd), use following code modified from Alex's answer:

    NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", nil];
    //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", nil];
    //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
    //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", nil];
    //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", nil];
    
    NSArray *arrLeft;
    NSArray *arrRight;
    
    NSRange range;
    range.location = 0;
    range.length = ([arrayTotal count] % 2) ? ([arrayTotal count] / 2) + 1 : ([arrayTotal count] / 2);
    
    arrLeft = [arrayTotal subarrayWithRange:range];
    
    range.location = range.length;
    range.length = [arrayTotal count] - range.length;
    
    arrRight = [arrayTotal subarrayWithRange:range];
    
    NSLog(@"Objects: %lu", (unsigned long)[arrLeft count]);
    NSLog(@"%@", [arrLeft description]);
    
    NSLog(@"Objects: %lu", (unsigned long)[arrRight count]);
    NSLog(@"%@", [arrRight description]);
    
    0 讨论(0)
  • 2020-12-06 11:11

    Have you tried adding nil to the end of the -initWithObjects: method?

    NSArray *leftArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]], nil];
    NSArray *rightArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]], nil];
    
    0 讨论(0)
提交回复
热议问题