Is there a way to rearrange an array of objects such that the contents are rearranged such that all the xth elements are grouped in another array? I’m not sure the best way to explain this so I’ll illustrate with an example:
theArray has 5 properties: number, color, size, height, quality. There are 50 instances of this array, each with different properties.
I want to rearrange this so there are 5 arrays with 50 items inside each array.
The way I would do it is:
NSMutableArray *innerTemp = [[NSMutableArray alloc] initWithCapacity:49];
NSMutableArray *outerTemp = [[NSMutableArray alloc] initWithCapacity:4];
for (int i = 0 ; i < [theArray count]; i++){
[innerTemp addObject:[[theArray objectAtIndex:i] number]];
[innerTemp addObject:[[theArray objectAtIndex:i] color]];
[innerTemp addObject:[[theArray objectAtIndex:i] height]];
[innerTemp addObject:[[theArray objectAtIndex:i] age]];
[innerTemp addObject:[[theArray objectAtIndex:i] quality]];
[outerTemp addObject:temp];
}
So I guess my question is, is there some easier way/more efficient to do this?
Just use KVC (Key Value Coding):
Assuming your class looks something like this:
and you have an array like
then this would be all you need:
This will do the trick.
Assuming your items in the
instancesarray are numbered from1..na call to[instances valueForKey:@"number"]would then return an NSArray like@[@1, @2, @3, @4, ...].