【问题标题】:NSMutableDictionary sort values in keysNSMutableDictionary 对键中的值进行排序
【发布时间】:2015-06-03 08:05:47
【问题描述】:

我有一个 NSMutableDictionary:

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

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

【问题讨论】:

    标签: ios dictionary nsdictionary nsmutabledictionary


    【解决方案1】:
    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];
    

    【讨论】:

      【解决方案2】:

      值-键对在存储在 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];
      }
      

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

      【讨论】:

        【解决方案3】:

        这是一种选择:

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

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

        【讨论】:

        • 如果我的值中有 NSObjects。我需要按这些对象具有的时间值对字典进行排序?
        • 因此您需要提供自己的自定义比较方法。看到这个 - stackoverflow.com/questions/805547/…
        猜你喜欢
        • 2012-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多