对NSMutableArray进行排序,它是NSMutableDictionary的值

时间:2015-03-27 04:22:54

标签: ios sorting nsmutablearray nsdictionary

我有几个键的NSMutableDictionary(NSDate是键),每个键的值是NSMutableArray,其对象是字典。每个字典都有NSDate“event_start_date”,我希望根据它对NSMutableArray进行排序。我怎样才能实现它?这是我的NSMutableDictionary的格式。

{
    "2015-03-23 18:30:00 +0000" =     (
                {
            "establishment_id" = 8;
            "event_end_date" = "2015-03-24 20:15:00";
            "event_image" = "";
            "event_name" = "Event One";
            "event_start_date" = "2015-03-24 19:15:00";
            miles = "0.17";
            "user_rate" = 0;
        }
    );
    "2015-03-24 18:30:00 +0000" =     (
                {
            "establishment_id" = 8;
            "event_end_date" = "2015-03-25 20:20:00";
            "event_image" = "";
            "event_name" = "Second Event";
            "event_start_date" = "2015-03-25 19:20:00";
            miles = "0.17";
            "user_rate" = 0;
        },
                {
            "establishment_id" = 8;
            "event_end_date" = "2015-03-30 01:00:00";
            "event_image" = "";
            "event_name" = getevent;
            "event_start_date" = "2015-03-25 01:00:00";
            miles = "0.17";
            "user_rate" = 0;
        },
                {
            "establishment_id" = 8;
            "event_end_date" = "2015-03-25 15:40:00";
            "event_image" = "";
            "event_name" = "TestAdd Event with note";
            "event_start_date" = "2015-03-25 14:40:00";
            miles = "0.17";
            "user_rate" = 0;
        }
    );
    "2015-03-26 18:30:00 +0000" =     (
                {
            "establishment_id" = 8;
            "event_end_date" = "2015-03-27 11:25:00";
            "event_image" = "http://venyounightout.com/images/1_2015_03_26_23_00_00.png";
            "event_name" = "Perfect event";
            "event_start_date" = "2015-03-27 10:25:00";
            miles = "0.17";
            "user_rate" = 0;
        }
    );
}

2 个答案:

答案 0 :(得分:0)

您可能无法对NSDictionary进行排序 - 但您可以对从字典中获取的数组进行排序。

// 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
}

答案 1 :(得分:0)

您可以使用以下NSMutableArray键对单个"event_start_date"词典进行排序:

[array sortUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"event_start_date" ascending:YES] ]];

要将其应用于字典中的每个值,您可以执行以下操作:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, NSMutableArray* array, BOOL *stop){
    [array sortUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"event_start_date" ascending:YES] ]];
}];