NSMutableDictionary 对键中的值进行排序

NSMutableDictionary sort values in keys

我有一个 NSMutableDictionary:

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

电影对象具有时间价值。我需要按 Movie.timeString 对每个键的值进行排序。我应该怎么做?

这是一种选择:

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

而您的 myNewDic 正是您所需要的。

值键对在 NSDictionaryNSMutableDictionary.

中存储时没有特定顺序

您可以通过遍历每个键来重写代码, 然后迭代地对值(存储为 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];
}

你可以试试这段代码,如果有任何问题,请告诉我。

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