问题
I have an array of class A objects, let it be detailsArray.
Class A has date, name as properties.
Can any one suggest a good method to sort this array based on date?
How can I use NSSortDescriptor
to sort this array? I know sorting array of dictionary using NSSortDescriptor
...
Any help is greatly appreciated.....
回答1:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortedArrayUsingDescriptors:@[sortDescriptor]];
回答2:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];
回答3:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [yourArray sortedArrayUsingDescriptors:sortDescriptors];
or you can use a block also
NSArray *sortedArray;
sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(A *a, A *b) {
NSDate *first = a.date;
NSDate *second = b.date;
return [first compare:second];
}];
回答4:
You need to give key forward by its class name, like
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ClassA.date" ascending:YES];
and do google your queries before ask any question, see the google crawler result.
来源:https://stackoverflow.com/questions/15540829/sorting-array-using-nssortdescriptor