簡體   English   中英

對NSDictionary的NSArray進行排序

[英]Sorting an NSArray of NSDictionary

我必須對一組字典進行排序,但我必須按字典中的對象排序。

將NSSortDescriptors與-sortedArrayUsingDescriptors一起使用: 對於鍵路徑,傳入字典鍵,然后傳入要對其進行排序的對象鍵。 在下面的示例中,您有一個字典數組,這些字典在“personDictionaryKey”下有一個人,而“person”有一個“lastName”鍵。

NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey:@"personInDictionary.lastName" 
        ascending:YES] autorelease]; // 1
NSArray * sortedArray = [unsortedArray sortedArrayUsingDescriptors:
        [NSArray arrayWithObject:descriptor]];

1 -在10.6中有創建排序描述符的類方便方法,但正如bbum的回答所說,現在有了啟用塊的排序方法,我認為它們的速度要快得多。 此外,我注意到你的問題是針對iOS的,所以這可能是無關緊要的。 :-)

改寫; 你想通過比較字典內容對數組進行排序? (即你知道你不能對字典的內容進行排序,對嗎?)

正如Joshua建議的那樣,使用NSSortDescriptorsortedArrayUsingDescriptors: . 這很可能是最好的解決方案; 至少最直截了當。

還有其他方法。

假設你的目標是iOS 4.0,那么你可以使用sortedArrayUsingComparator:並傳遞一個塊,它將對兩個字典的內容進行比較。

如果您的目標是iOS 3.x(包括iPad),那么您將使用sortedArrayUsingFunction:context: .

或者,正如Joshua建議的那樣,使用NSSortDescriptorsortedArrayUsingDescriptors:

所有這些都有很好的記錄,有例子。

這是一個使用自定義對象而不是字典的實現:

ArtistVO *artist1 = [ArtistVO alloc];
artist1.name = @"Trentemoeller";
artist1.imgPath = @"imgPath";

ArtistVO *artist2 = [ArtistVO alloc];
artist2.name = @"ATrentemoeller";
artist2.imgPath = @"imgPath2";


ArtistVO *artist3 = [ArtistVO alloc];
artist3.name = @"APhextwin";
artist3.imgPath = @"imgPath2";    

//NSLog(@"%@", artist1.name);
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:artist1];
[arr addObject:artist2];
[arr addObject:artist3];


NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
  initWithKey:@"name"
  ascending:YES
  selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];    

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

NSLog(@"\nSorted ...");
NSEnumerator *enumerator;
enumerator = [sortedArray objectEnumerator];

ArtistVO *tmpARt;
while ((tmpARt = [enumerator nextObject])) NSLog(@"%@", tmpARt.name);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM