问题
I have Problem related to array Sorting.
I have an NSMutable array say's A.Which has an class object b on its each index.
class b contain's multiple field Like int,string and nsdate.
I want to sort the A array on the basis of class b time(NSdate) ascendingly.
I follow the date sorting question on stackoverflow but that's only for date array.
Sort NSArray of date strings or objects
Kindly guide me.
Thank's in advance
回答1:
Here you go just modify some part of code for your requirement
- (NSArray *)sortedWeightEntriesByWeightDate:(NSArray *)unsortedArray {
NSMutableArray *tempArray = [NSMutableArray array];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:0];
@try {
for(int i = 0; i < [unsortedArray count];i++) {
NSDateFormatter *df = [[NSDateFormatter alloc]init];
MyDataModal *entry = [unsortedArray objectAtIndex:i];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [df dateFromString:entry.weightDate];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if(date) {
[dict setObject:entry forKey:@"entity"];
[dict setObject:date forKey:@"date"];
[tempArray addObject:dict];
}
[df release];
}
NSInteger counter = [tempArray count];
NSDate *compareDate;
NSInteger index;
for(int i = 0 ; i < counter; i++) {
index = i;
compareDate = [[tempArray objectAtIndex:i] valueForKey:@"date"];
NSDate *compareDateSecond;
for(int j = i+1 ; j < counter; j++) {
compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:@"date"];
NSComparisonResult result = [compareDate compare:compareDateSecond];
if(result == NSOrderedDescending) {
compareDate = compareDateSecond;
index=j;
}
}
if(i!=index)
[tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
}
NSInteger counterIndex = [tempArray count];
for(int i = 0; i < counterIndex ; i++) {
[sortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:@"entity"]];
}
}
@catch (NSException * e) {
NSLog(@"An exception occured while sorting weight entries by date");
}
@finally {
return [NSArray arrayWithArray:sortedArray];
}
}
回答2:
How about:
NSArray *myArray = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture], @"theDate", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantPast], @"theDate", nil],
nil];
NSLog(@"Before sorting: %@", myArray);
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"theDate" ascending: YES];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject: dateSortDescriptor]];
NSLog(@"After Sorting: %@", sortedArray);
This presumes that the date you want to sort for has a key (it is a property, essentially.)
来源:https://stackoverflow.com/questions/6798977/objects-sorting-with-date-time-problem-in-arrayiphone-development