有没有办法重新排列数组列表的内容?

时间:2013-01-30 14:46:21

标签: objective-c

有没有办法重新排列对象数组,以便重新排列内容,使所有x th 元素在另一个数组中分组?我不确定解释这个问题的最好方法,所以我将举例说明:

theArray有5个属性:数量,颜色,大小,高度,质量。这个数组有50个实例,每个实例都有不同的属性。

我想重新安排这个,所以每个阵列中有5个阵列,每个阵列有50个项目。

我这样做的方式是:

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];
}

所以我想我的问题是,有更简单的方法/更高效的方法吗?

1 个答案:

答案 0 :(得分:2)

只需使用KVC(Key Value Coding):

假设你的班级看起来像这样:

@interface InstanceClass : NSObject

// IIRC properties need to be objects (hence the NSValue around NSSize), there is no auto-wrapping.
@property (readwrite, strong, nonatomic) NSNumber *number;
@property (readwrite, strong, nonatomic) NSColor *color;
@property (readwrite, strong, nonatomic) NSValue *sizeValue;
@property (readwrite, strong, nonatomic) NSNumber *height;
@property (readwrite, strong, nonatomic) NSNumber *quality;

@end

你有一个像

这样的数组
NSArray *instances = @[instance1, instance2, instance3, instance4, ...];

那么这就是你所需要的:

NSArray *numbers   = [instances valueForKey:@"number"];  // array of numbers.
NSArray *colors    = [instances valueForKey:@"color"];   // array of colors.
NSArray *sizes     = [instances valueForKey:@"size"];    // array of sizes.
NSArray *heights   = [instances valueForKey:@"height"];  // array of heights.
NSArray *qualities = [instances valueForKey:@"quality"]; // array of qualities.

这样就可以了。

假设instances数组中的项目编号为1..n,则[instances valueForKey:@"number"]的调用将返回 NSArray ,如@[@1, @2, @3, @4, ...]。< / p>