Sorting Array Using NSSortDescriptor [duplicate]

♀尐吖头ヾ 提交于 2019-12-04 13:10:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!