Splitting array

Discussion in 'Mac Programming' started by bker, May 26, 2010.

  1. bker macrumors newbie

    Joined:
    May 22, 2010
    #1
    Hi,
    I want to re-arrange and split an array into 4 arrays in Obj-C like this:

    array: (AA,EE)
    array: (BB,FF)
    array: (CC,GG)
    array: (DD,HH)

    Can you please help me. Thank!

    PHP:
    2010-05-27 01:38:05.745 Untitled[38119:10b] array:(
        
    AA,
        
    BB,
        
    CC,
        
    DD,
        
    EE,
        
    FF,
        
    GG,
        
    HH
    )
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    Code:
    NSArray *myArray = [NSArray arrayWithObjects: @"AA",@"CC",@"BB",@"FF",@"EE",@"DD",nil];
    myArray = [myArray sortUsingSelector:@selector(compare:)];
    NSMutableArray *myTwoDArray = [[NSMutableArray alloc] init];
    NSUInteger mySize = [myArray size]; 
    for(NSUInteger pos = 0; pos < mySize/2 + 1;pos++) {
      NSUInteger secondPos = mySize/2+pos+(mySize%2);
      if(secondPos>=mySize) {
        [myTwoDArray addObject:[NSArray arrayWithObjects:[myArray objectAtIndex:pos],nil]];
      } else {
        [myTwoDArray addObject:[NSArray arrayWithObjects:[myArray objectAtIndex:pos],[myArray objectAtIndex:secondPos],nil]];
      }
    }
    
    At the end of the loop myTwoDArray should be a list of NSArrays, each two long with the last being one long if the original list has an odd number of elements. myArray is autoreleased, so myTwoDArray is the only object you own at the end of this code.

    Note this was written on my phone and has not been compiled or tested. Hopefully the general idea was expressed.

    -Lee
     
  3. bker thread starter macrumors newbie

    Joined:
    May 22, 2010
    #3
    Thank you Lee for the help with explanation!!!
     

Share This Page