可以像这样对数组进行排序:
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];
可以订购一对吗? 在此先感谢:)
答案 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);
工作流:
从数组创建字典->
排序字典->
从字典创建数组。
修改强>
使用NSSortDescriptor
与ascending: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 Player
和name
创建一些新对象让我们说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];