2012-07-21 28 views
-2

我有一個小疑問,就是我有一個包含以下4個對象一個NSArray:如何按照字母順序與第一號排序一個NSArray

Genesis, 1 Kings, leviticus, 2 Kings 

我要排序此數組中的字典順序像我想要一個像這樣的預期輸出

1 Kings, 2 Kings, Genesis, leviticus 

這是如何實現的?

+3

你看的NSArray的文檔? NSArray提供了許多排序方法。 – Caleb 2012-07-21 09:57:03

+0

這就是爲什麼我已經提供了詳細的文檔鏈接的答案,所以這個用戶將去文檔和探索更多。 – Hemang 2012-07-21 09:58:28

回答

6

轉到此鏈接:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html#//apple_ref/doc/uid/20000132-SW5

這是蘋果的文檔,你的問題就解決了那邊。

查看示例。

//First create the array of dictionaries 
NSString *last = @"lastName"; 
NSString *first = @"firstName"; 

NSMutableArray *array = [NSMutableArray array]; 
NSArray *sortedArray; 

NSDictionary *dict; 
dict = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Jo", first, @"Smith", last, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Joe", first, @"Smith", last, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Joe", first, @"Smythe", last, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Joanne", first, @"Smith", last, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Robert", first, @"Jones", last, nil]; 
[array addObject:dict]; 

//Next we sort the contents of the array by last name then first name 

// The results are likely to be shown to a user 
// Note the use of the localizedCaseInsensitiveCompare: selector 
NSSortDescriptor *lastDescriptor =[[NSSortDescriptor alloc] initWithKey:last 
          ascending:YES 
          selector:@selector(localizedCaseInsensitiveCompare:)]; 
NSSortDescriptor *firstDescriptor = 
[[NSSortDescriptor alloc] initWithKey:first 
          ascending:YES 
          selector:@selector(localizedCaseInsensitiveCompare:)]; 

NSArray *descriptors = [NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil]; 
sortedArray = [array sortedArrayUsingDescriptors:descriptors]; 

此代碼是蘋果文檔中的一個示例。

我希望它能幫助你。

謝謝,

Hemang。

5

您可以排序的字母順序NSString像這樣的數組:

NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];