对NSMutableArray进行排序并对另一个NSMutableArray进行排序

时间:2012-08-10 16:30:40

标签: iphone objective-c ios xcode arrays

可以像这样对数组进行排序:

MutableArray  = [NSMutableArray arrayWithObjects:@"5",@"1",@"7,@"9",@"4", nil];

to(小头开始):

MutableArray  = [NSMutableArray arrayWithObjects:@"9",@"7",@"5,@"4",@"1", nil];

是否也可以对两个数组进行排序:

MutableArray  = [NSMutableArray arrayWithObjects:@"5",@"1",@"7",@"9",@"4", nil];
MutableArray  = [NSMutableArray arrayWithObjects:@"Andy",@"Mike",@"Bob",@"Amy",@"Alex", nil];

to(从大到小,但Andy得到5点,Mike得到1等等:

MutableArray  = [NSMutableArray arrayWithObjects:@"9",@"7",@"5",@"4",@"1", nil];
MutableArray  = [NSMutableArray arrayWithObjects:@"Amy",@"Bob",@"Andy",@"Alex",@"Mike", nil];

可以订购一对吗? 在此先感谢:)

2 个答案:

答案 0 :(得分:1)

示例如何排序arrayOne升序并对arrayTwo进行排序:

NSMutableArray *arrayOne  = [NSMutableArray arrayWithObjects:@"5",@"1",@"7",@"9",@"4", nil];
NSMutableArray *arrayTwo = [NSMutableArray arrayWithObjects:@"Andy",@"Mike",@"Bob",@"Amy",@"Alex", nil];

NSDictionary *temp = [NSDictionary dictionaryWithObjects:arrayTwo forKeys:arrayOne];
NSArray *sortedArrayOne = [[temp allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *sortedArrayTwo = [temp objectsForKeys:sortedArrayOne notFoundMarker:[NSNull null]];

NSLog(@"%@",sortedArrayOne);
NSLog(@"%@",sortedArrayTwo);

工作流:
从数组创建字典->排序字典->从字典创建数组。

修改

使用NSSortDescriptorascending:NO对降序排序,快速示例:

NSDictionary *temp = [NSDictionary dictionaryWithObjects:arrayTwo forKeys:arrayOne];
NSSortDescriptor *theDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(compare:)];    
NSArray *sortedArrayOne = [[temp allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:theDescriptor]];
NSArray *sortedArrayTwo = [temp objectsForKeys:sortedArrayOne notFoundMarker:[NSNull null]];

答案 1 :(得分:0)

为什么不用ivars Playername创建一些新对象让我们说score,并将该类的实例存储在数组中。然后,您就可以根据需要对代码中的任何一点对该数组进行排序,如下所示:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedByName = [players sortedArrayUsingDescriptors:sortDescriptors];

或得分:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedByName = [players sortedArrayUsingDescriptors:sortDescriptors];