Reputation: 180
Can you help me on sorting (ascending order) the array contains NSDate
.
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
[tempArray addObject: NSDate1];
[tempArray addObject: NSDate2];
[tempArray addObject: NSDate3];
[tempArray addObject: NSDate4];
Upvotes: 2
Views: 705
Reputation: 252
Use below code:
[your array sortUsingComparator:
^NSComparisonResult(id obj1, id obj2){
obj1 *o1 = (obj1*)obj1;
obj2 *o2 = (obj2*)obj2;
if (o1.personAge > 02.personAge) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}
];
Upvotes: 1
Reputation: 1398
[array1 sortUsingComparator: (NSComparator)^(NSString *key1, NSString *key2)
{
return [key2 compare: key1];
}
];
If you want array in ascending or descending order just change
compare
return [key1 compare: key2];
Upvotes: 0
Reputation: 162
Best way to do this,use sort descriptor.
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"self.dueDate" ascending:YES comparator:^NSComparisonResult(NSDate *dateObject1, NSDate *dateObject2) {
return [dateObject1 compare:dateObject2];
}];
Upvotes: 0
Reputation: 285079
Since NSDate
responds to compare
and the default sorting order is ascending, the simplest way is
[tempArray sortUsingSelector:@selector(compare:)];
Upvotes: 1
Reputation: 109
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"self.dueDate" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *date1 = [dateFormat dateFromString:obj1];
NSDate *date2 = [dateFormat dateFromString:obj2];
return [date1 compare:date2];
}];
Upvotes: 0