Nsmutablearray *array = [[Nsmutablearray alloc] initwithobjects:@ "2019/03/01/" @ "2013/03/02", @ "2013/03/07", @ "2014/ 03/01/", [NSNull null], nil]; Array = (Nsmutablearray *) [array sortedarrayusingcomparator:^nscomparisonresult (ID obj1, id obj2) { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [Formatter setdateformat:@ "yyyy/mm/dd/"]; if (obj1 = = [NSNull null]) { obj1 = @ "0000/00/00"; } if (obj2 = = [NSNull null]) { obj2 = @ "0000/00/00"; } NSDate *date1 = [formatter datefromstring:obj1]; NSDate *date2 = [formatter datefromstring:obj2]; Nscomparisonresult result = [Date1 compare:date2]; return result = = nsorderedascending; }]; for (int i = 0; i < [array count]; i++) { NSLog (@ "%@", [array objectatindex:i]); }
in the project need to sort the data, here to simulate an array, because the item returned in the JSON key corresponding to the value of NULL, so when ordering the need to determine whether obj1 and Obj2 is empty, there are ascending and descending problems according to
return result = = nsorderedascending; Ascending
return result = = Nsordereddescending; Descending
Ascending result:
2015-06-16 17:16:14.930 testh5[15888:669365] 2019/03/01/2015-06-16 17:16:14.930 testh5[15888:669365] 2014/03/01/ 2015-06-16 17:16:14.931 testh5[15888:669365] 2013/03/072015-06-16 17:16:14.931 testh5[15888:669365] 2013/03/ 022015-06-16 17:16:14.931 testh5[15888:669365] <null>
Descending result:
2015-06-16 17:17:21.692 testh5[15946:671080] 2013/03/022015-06-16 17:17:21.692 testh5[15946:671080] 2013/03/ 072015-06-16 17:17:21.692 testh5[15946:671080] 2014/03/01/2015-06-16 17:17:21.692 TestH5[15946:671080] 2019/03/01/ 2015-06-16 17:17:21.692 testh5[15946:671080] <null>
iOS to sort dates