i'm having a set of Dictionaries in a NSMutableArray. now i want to sort ascending & Descending order by time here is my Array value.
(
{
StartTime = "09:00 AM";
TravelsName = "ABC Travels";
},
{
StartTime = "07:30 AM";
TravelsName = "XYZ Travels ";
},
{
StartTime = "06:45 PM";
TravelsName = "GSP Travels";
},
{
StartTime = "05:00 PM";
TravelsName = "Madura Travels";
},
{
StartTime = "12:45 AM";
TravelsName = "MJT Travels";
},
{
StartTime = "12:45 PM";
TravelsName = "OPR Travels";
},
{
StartTime = "01:00 AM";
TravelsName = "VMS Travels";
}
)
Please help me i had sorted the set of NSDate inside the NSMutableArray by the below code
//To sort the Time Array
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:times.count];
for (NSString *timeString in times)
{
NSDate *date = [dateFormatter dateFromString:timeString];
[dates addObject:date];
}
[dates sortUsingSelector:@selector(compare:)];
NSMutableArray *sortedTimes = [NSMutableArray arrayWithCapacity:dates.count];
for (NSDate *date in dates)
{
NSString *timeString = [dateFormatter stringFromDate:date];
[sortedTimes addObject:timeString];
}
but i don't know how to sort the Dictionary in the NSMutableArray help me.
It is best to use the sorting methods that are already provided in NSArray
. Something like this should do:
NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
return [obj1[@"StartTime"] compare:obj2[@"StartTime"]];
}];
Or if the StartTime
is still a string:
NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
return [[dateFormatter dateFromString:obj1[@"StartTime"]] compare:[dateFormatter dateFromString:obj2[@"StartTime"]]];
}];
To change the ascending/descending order you simply swap the obj1
and obj2
when used in the block:
return [obj2[@"StartTime"] compare:obj1[@"StartTime"]];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.