ios 按字典中键的值对字典的 NSArray 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9509138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting NSArray of dictionaries by value of a key in the dictionaries
提问by manuelBetancurt
I have an array populated by dictionaries, and I need to sort the array alphabetically by the values of one of the keys of the dictionaries.
我有一个由字典填充的数组,我需要按字典的其中一个键的值按字母顺序对数组进行排序。
This is my array:
这是我的数组:
tu dictus: (
{
brand = Ryul;
productTitle = Any;
quantity = 1;
subBrand = "Ryul INJ";
type = Product;
},
{
brand = Trol;
productTitle = Different;
quantity = 2;
subBrand = "";
type = Brand;
},
{
brand = Dtor;
productTitle = Any;
quantity = 1;
subBrand = "";
type = Product;
},
{
brand = Ryul;
productTitle = Different;
quantity = 2;
subBrand = "Ryul CHES";
type = SubBrand;
},
{
brand = Anan;
productTitle = Any;
quantity = 1;
subBrand = "";
type = Product;
}
)
Normally for sorting an array I will use
通常用于排序我将使用的数组
myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
But how do sort using the brand
key of the dictionary?
但是如何使用brand
字典的键进行排序呢?
回答by QED
I think this will do it:
我认为这会做到:
brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
I pulled the code from Sort Descriptor Programming Topics. Also, Key-Value Codingcomes into play, in that sortedArrayUsingDescriptors:
will send a valueForKey:
to each element in myArray
, and then use standard comparators to sort the returned values.
我从Sort Descriptor Programming Topics 中提取了代码。此外,键值编码开始发挥作用,sortedArrayUsingDescriptors:
它将向 中的valueForKey:
每个元素发送myArray
,然后使用标准比较器对返回值进行排序。
回答by Prabhu Natarajan
We Got The Solution By Using The Method Follows
我们通过使用以下方法得到了解决方案
[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];
Where:-
在哪里:-
jsonData
- MutableArray Which holds the Parsed JSON Data.
jsonData
- MutableArray 保存解析的 JSON 数据。
fullname
- the data we want to sort.
fullname
- 我们要排序的数据。
id
- An unique data which comes with the inner dictionary.
id
- 内部字典附带的唯一数据。
回答by HDmast
In switf:
在 swf 中:
var descriptor: NSSortDescriptor = NSSortDescriptor(key: "brand", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])
回答by Meet Doshi
Use following code for sort using the "brand" key from the dictionary..
使用以下代码使用字典中的“品牌”键进行排序..
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);
Use following code, If you to sorting according two keys from the dictionary; Like, "brand" key and productTitle key from the dictionary:-
使用以下代码,如果您从字典中根据两个键进行排序;比如,字典中的“品牌”键和产品标题键:-
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"productTitle" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
NSArray * sortedArray = [feedData sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);
回答by Hardip Kalola
arrSorted = [arrBrand sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([[obj1 valueForKey:@"iUserId"] integerValue] > [[obj2 valueForKey:@"iUserId"] integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([[obj1 valueForKey:@"iUserId"] integerValue] < [[obj2 valueForKey:@"iUserId"] integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
回答by mylogon
As an addition to QED's code,
作为 QED 代码的补充,
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:@[brandDescriptor]];
This clarifies the classes of the variables and optimises the array creation with fast-enumeration. Thanks
这就说明变量的类,并优化快速枚举数组创建。谢谢
回答by OffensivelyBad
My code was crashing when using NSSortDescriptor
so ended up using a block which works great in my use case, where I am expecting the "rank" to be an NSNumber. If the object can't be converted to an integer it will not sort but it also won't cause a crash.
我的代码在使用时崩溃了,NSSortDescriptor
所以最终使用了一个在我的用例中效果很好的块,我希望“排名”是一个 NSNumber。如果对象无法转换为整数,则不会排序,但也不会导致崩溃。
NSArray *sortedArray = [data sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
long data1 = [[obj1 valueForKey:@"rank"] integerValue];
long data2 = [[obj2 valueForKey:@"rank"] integerValue];
if (data1 > data2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (data1 < data2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
回答by jbchitaliya
NSSortDescriptor *brandDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Position" ascending:YES selector:@selector(localizedStandardCompare:)] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray *sortedArray = [arrTemp sortedArrayUsingDescriptors:sortDescriptors];
array_PreLagData=(NSMutableArray*)sortedArray;
unsorted array
Printing description of arrTemp:
<__NSArrayM 0x10282100>(
{
Milker2 = "11:03:17 AM";
Position = 2;
},
{
Milker1 = "11:03:28 AM";
Position = 25;
},
{
Milker3 = "11:03:18 AM";
Position = 3;
},
{
Milker1 = "11:03:16 AM";
Position = 1;
Strip = "11:32:32 AM";
},
{
Milker1 = "11:03:21 AM";
Position = 10;
}
)
Sorted array
<__NSArrayI 0x101363c0>(
{
Milker1 = "11:03:16 AM";
Position = 1;
Strip = "11:32:32 AM";
},
{
Milker2 = "11:03:17 AM";
Position = 2;
},
{
Milker3 = "11:03:18 AM";
Position = 3;
},
{
Milker1 = "11:03:21 AM";
Position = 10;
},
{
Milker1 = "11:03:28 AM";
Position = 25;
}
)
[enter link description here][1]
[1]: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE
回答by IOS Rocks
Just try it out easiest way...
只需尝试最简单的方法...
myArray = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
[tempArray addObjectsFromArray: myArray];
NSString *key = @"brand";
NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:brandDescriptor,nil];
NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];
[brandDescriptor release];
[tempArray removeAllObjects];
tempArray = (NSMutableArray*)sortedArray;
[myArray removeAllObjects];
[myArray addObjectsFromArray:tempArray];
回答by alok
you can do this .
你可以这样做 。
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d LLLL yyyy"];
NSComparator compareDates = ^(id string1, id string2)
{
NSDate *date1 = [formatter dateFromString:string1];
NSDate *date2 = [formatter dateFromString:string2];
return [date1 compare:date2];
};
NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO comparator:compareDates];
[array sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc1, nil]];