开发者

How do I sort an NSMutableArray?

I have the following NSMutableArrays:

NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"AAA",@"BBB",@"CCC",nil];
NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:@"BBB",@"AAA",@"CCC",nil];
NSMutableArray *array3 = [[NSMutableArray alloc]initWithObjects:@"CCC",@"BBB",@"AAA",nil];

NSMutableArray *number = [[NSMutableArray alloc]initWithCapacity:3]; <- use sorting key.

NSNumber *number1 = [[NSNumber alloc]initWithInt:30];
NSNumber *number2 = [[NSNumber alloc]initWithInt:20];
NSNumber *number3 = [[NSNumber alloc]initWithInt:10];
[number ad开发者_JAVA技巧dObject:number1];
[number addObject:number2];
[number addObject:number3];

But I want to get this result:

// get results to sorted by number key

// number result :    10,   20,   30
// array1 result :   CCC,  BBB,  AAA
// array2 result :   CCC,  AAA,  BBB
// array3 result :   AAA,  BBB,  CCC

How would I go about doing this?


I think what you are asking for is to sort multiple arrays into the same relative order as a controlling array? In which case, if you can sort one array, just apply the same transforms to the other arrays as you sort the first?


See the documentation for -sortedArrayUsing... methods. You'll probably want to implement your own comparator block.


I would go about this differently. I would define one class that contains three strings and an integer, and put the instances of that class in a single array. When you sort the array, you sort on the integer, and the rest gets moved along with it automatically.

@interface QuadrupleItems : NSObject
{
    NSString *first;
    NSString *second;
    NSString *third;
    NSInteger integer;
}
// ... methods you might need, e.g. initWithFirst:second:third:integer: etc...
@property (retain) NSString *first;
// etc...

Now, sorting is easy, and I guess you already know you can use sortedArrayUsing: to sort the array. In the block, you compare the integer properties of the items.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜