[英]Best way to sort an NSArray of NSDictionary objects?
我正在努力嘗試對字典進行排序。
我的詞典具有一些興趣,價格,受歡迎程度等值。
有什么建議么?
像這樣使用NSSortDescriptor
。
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];
stories
是您要排序的數組。 recent
是另一個可變的數組,已對字典值進行排序。 用必須排序的鍵值更改@"interest"
。
祝一切順利
[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
我真的不想將其分成多行。 對我來說已經足夠簡單了。
您可以從父級遍歷到所需的子級屬性。 例如
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child" ascending:YES];
Update,sortUsingDescriptors現在是sortedArrayUsingDescriptors
因此,它像:
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
編寫一個排序函數,比較兩個字典中的相關字段。 使用此版本時,例如可以使用NSArray#sortedArrayUsingFunction:context:
對數組進行排序。
請參見NSArray類參考
array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
記住分配給數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.