Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

bker

macrumors newbie
Original poster
May 22, 2010
6
0
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
)
 
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.