按字母顺序排序NsmutableDictionary

时间:2016-05-03 10:03:10

标签: ios objective-c sorting nsmutabledictionary

我有一个dictionary,其中,对于一个密钥(例如密钥“0”),有一个key value pair data。密钥类似于name,id,p_id。我想对NSMutableDictionary排序与Key“name”相关的值。 dictionary中的数据如下,

 0 =     {
        id = 12;
        name = "Accounts ";
        "p_id" = 13222071;
    };
    1 =     {
        id = 13;
        name = "consultant";
        "p_id" = 15121211;
    };
    2 =     {
        id = 11;
        name = "Tania";
        "p_id" = 10215921;
    };
}

感谢任何帮助!

4 个答案:

答案 0 :(得分:1)

请试用以下代码:

        [yourMutableArray sortUsingComparator: (NSComparator)^(NSDictionary *a, NSDictionary *b) {
             NSString *key1 = [a objectForKey: @"name"];
             NSString *key2 = [b objectForKey: @"name"];

             return [key1 compare: key2];
        }];

        NSLog(@"Sorted Array By name key : %@", yourMutableArray);

希望这有帮助!

答案 1 :(得分:0)

NSArray *sortedKeys = [dict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *d1, NSDictionary *d2) {
    return [d1[@"name"] compare:d2[@"name"]];
}];

NSArray *objects = [dict objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];

答案 2 :(得分:0)

Dictionaries未排序,与任何订单都不相似。你应该做的是首先获得所有keys。然后在键上应用sort method,然后根据订购的键请求对象。

E.g:

NSArray *keys = [dictionary allKeys];
NSArray *sortedKeys = <sort the keys according to your preferred method>

现在,您可以从数组sortedKeys的顺序迭代Dictionary。

答案 3 :(得分:0)

虽然已经非常清楚地表明字典无法正确排序,但这并不意味着你无法实现目标。这段代码将为您完成:

    NSArray *arrayOfDicts = dic.allValues; //Now we got all the values. Each value itself is a dictionary so what we get here is an array of dictionaries

    NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; //Create sort descriptor for key name
    NSArray *sortingDesc = [NSArray arrayWithObject:nameDescriptor];
    NSArray *sortedArray = [arrayOfDicts sortedArrayUsingDescriptors:sortingDesc]; //Get sorted array based on name

    NSMutableDictionary *kindaSortedDict = [[NSMutableDictionary alloc] init];
    int keyForDict=0;
    for(NSDictionary *valDict in sortedArray)
    {
        [kindaSortedDict setObject:valDict forKey:[NSString stringWithFormat:@"%i",keyForDict]]; //Set values to our new dic which will be kind of sorted as the keys will be assigned to right objects
        keyForDict++;
    }

    //Now you can simply get sorted array of keys from kindaSortedDic and results for them will always be sorted alphabetically. Alternatively you can just skip all that bother and directly use sortedArray

我在代码中添加了注释,以帮助您理解这一点。

为了访问已排序的值,我会这样做:

NSArray *sortedKeys = [kindaSortedDict.allKeys sortedArrayUsingDescriptors:
                    @[[NSSortDescriptor sortDescriptorWithKey:@"intValue" 
                                                    ascending:YES]]];
for(NSString *key in sortedKeys)
{
   NSDictionary *valDict = [kindaSortedDict objectForKey: key];
   NSLog(@"Dict is: %@ for key: %@",valDict,key);
}