Sort NSDictionary keys as NSDate

前端 未结 2 916
梦如初夏
梦如初夏 2021-01-13 23:29

I\'m developing an iOS 4 application with latest SDK and XCode 4.2.

I have a NSMutableDictionary where keys are NSDate and

相关标签:
2条回答
  • 2021-01-14 00:09

    Try this code:

    NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
    

    But note that you cannot sort a dictionary, as it is based on key-value lookups, not indexed lookups.

    0 讨论(0)
  • 2021-01-14 00:12

    That's a pretty standard thing, however, you may not sort an NSDictionary - you may sort an array you get from the dictionary however.

    This is what I'd do:

    // get all keys into array
    NSArray * keys = [your_dictionary allKeys];
    
    // sort it
    NSArray * sorted_keys = [keys sortedArrayUsingSelector:@selector(compare:)];
    
    // now, access the values in order
    for (NSDate * key in sorted_keys)
    {
      // get value
      NSMutableString * your_value = [your_dictionary valueForKey: key];
    
      // perform operations
    }
    
    0 讨论(0)
提交回复
热议问题