2012-08-10 53 views
0

這可能有點像這樣的數組:排序的NSMutableArray和排序其他的NSMutableArray沿

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

到(啓動大結束小):

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

(從大至小,但Andy5點,Mike得到了1等):

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

是否有可能對他們下令爲一對夫婦?
感謝提前:)

+1

你最好來看看的NSDictionary,似乎... – meronix 2012-08-10 16:32:50

+6

是它的所謂排序 – 2012-08-10 16:32:52

+0

爲什麼nsdictionary? – Lollo 2012-08-10 16:35:57

回答

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]]; 
+0

謝謝:)工作很棒:)但有可能做相反的事情嗎?而不是1,4,5,7,9然後得到它9,7,5,4,1(與名字)? – Lollo 2012-08-10 18:19:26

+0

添加了快速示例如何對降序進行排序。 – Anne 2012-08-10 20:38:15

+0

如果我使用數字22,它將位於1和4之間..如何改變它? – Lollo 2012-08-10 20:44:14

0

你爲什麼不只是創造一些新的對象,讓我們說Player與高德namescore和存儲實例數組中的那個類。然後,你就可以作爲你想數組排序任何點在你的代碼如下所示:

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