NSMutableDictionary在键中排序值

时间:2015-03-30 10:36:28

标签: ios dictionary nsdictionary nsmutabledictionary

我有一个NSMutableDictionary:

NSMutableDictionary = {
    "03-19" = (
            "Movie1", 
            "Movie2", 
            "Movie3"
        );
    "03-20" = (
            "Movie1"
        );
    "03-21" = (
            "Movie1", 
            "Movie2"
        );
}

电影对象具有时间价值。我需要通过Movie.timeString为每个键排序值。我该怎么做?

3 个答案:

答案 0 :(得分:1)

当存储在 NSDictionary NSMutableDictionary 中时,价值密钥对没有特别的顺序。

您可以通过迭代每个键重新编写代码, 然后迭代地对这些值(存储为NSArray / NSMutableArray对象,我推测)进行排序。 假设它确实是 NSMutableDictionary * dict

for(NSString *key in [dict allKeys])
{
NSArray *arrTimes = [dict objectForKey:key];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];

NSArray *arrSortedTimes = [arrTimes sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];
    return [date1 compare:date2];
}];

[dict setObject:arrSortedTimes forKey:key];
}

如果您遇到任何问题,可以试试这段代码,并告诉我。

答案 1 :(得分:0)

这是一个选项:

   NSMutableDictionary *myNewDic = [NSMutableDictionary dictionary];
   for (NSString *key in [myDictionary allKeys]) {
       [myNewDic setObject:[[myDictionary objectForKey:key] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] forKey:key];
   }

你的myNewDic就是你需要的那个。

答案 2 :(得分:0)

NSDictionary *dictionary = @{@"1": @"some value 1",
                             @"5": @"some value 5",
                             @"2" : @"some value 2"};
NSArray *sortedKeys = [dictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [obj1 compare:obj2 options:0];
}];
NSDictionary *sorted = [NSDictionary dictionaryWithObjects:[dictionary objectsForKeys:sortedKeys notFoundMarker:@""] forKeys:sortedKeys];