按字典中键的值对字典的NSArray进行排序

时间:2012-03-01 00:54:52

标签: ios objective-c sorting nsarray nsdictionary

我有一个由字典填充的数组,我需要按照字典中某个键的值按字母顺序对数组进行排序。

这是我的阵列:

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;
}
)

通常,我会使用

对数组进行排序
myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

但是如何使用字典的brand键进行排序?

11 个答案:

答案 0 :(得分:109)

我认为这样做会:

brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

我从Sort Descriptor Programming Topics提取代码。此外,Key-Value Coding开始发挥作用,sortedArrayUsingDescriptors:会向valueForKey:中的每个元素发送myArray,然后使用标准比较器对返回的值进行排序。

答案 1 :(得分:9)

我们通过使用方法得到了解决方案

[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];

其中: -

jsonData - MutableArray,其中包含解析的JSON数据。

fullname - 我们想要排序的数据。

id - 内部字典附带的唯一数据。

答案 2 :(得分:4)

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

答案 3 :(得分:4)

在switf:

<select multiple="" id="e2" tabindex="-1" class="select2-hidden-accessible" name="e2" aria-hidden="true">
    <option value="PDS.RICE">PDS.RICE</option>
    <option value="PDS.WHEAT">PDS.WHEAT</option>
    <option value="PDS.DAL CHANNA">PDS.DAL CHANNA</option>
    <option value="PDS.DAL KALA CHANNA">PDS.DAL KALA CHANNA</option>
</select>

答案 4 :(得分:4)

使用以下代码进行排序,使用&#34;品牌&#34;字典中的密钥..

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

使用以下代码,如果要根据字典中的两个键进行排序;喜欢&#34;品牌&#34;字典中的key和productTitle键: -

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

答案 5 :(得分:3)

作为QED代码的补充,

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:@[brandDescriptor]];

这澄清了变量的类,并使用快速枚举优化了数组创建。 感谢

答案 6 :(得分:2)

我的代码在使用NSSortDescriptor时崩溃,所以最终使用了一个在我的用例中运行良好的块,我期待&#34; rank&#34;成为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;
}];

答案 7 :(得分:1)

试试最简单的方法......

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

答案 8 :(得分:1)

你可以这样做。

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

答案 9 :(得分:1)

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

答案 10 :(得分:0)

使用此快捷键4

let sortedArray = arrayTobeSort.sorted {$0["keyName"].compare($1["keyName"]) == ComparisonResult.orderedAscending}

您还可以使用 ComparisonResult.orderedDescending 以降序排序

相关问题