[英]How to sort NSMutableArray of object in ascending or descending order
[英]How to sort NSMutableArray in ascending order, iPhone?
我有SQLite数据库(DB)并将其作为模型类并在NSMutableArray中获取数据库。 我的DB与此DB类似。 学生名称| RegisterNumber | DatesOfJoin(DoJ)我在tableView中成功显示了DoJ,但我想在tableView中按升序和降序排序DatesOfJoin。 任何帮助将不胜感激,并提前感谢您。
您可以使用NSSortDescriptor
和sortUsingDescriptors:sortDescriptors
对可变数组进行排序。
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DatesOfJoin" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];
请查看官方文档: http : //developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSArray_Class/NSArray.html
你有很多方法来对数组进行排序:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
- (NSArray *)sortedArrayUsingSelector:(SEL)comparator
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr
对于降序:
NSArray *sorted = [Arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] < [obj2 intValue]) return NSOrderedDescending;
else return NSOrderedAscending;
}];
对于Asending Order:
NSArray *sorted = [Arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
else return NSOrderedDescending;
}];
您可以尝试使用:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"Over here your key" ascending:YES]; //Just write the key for which you want to have sorting & whole array would be sorted.
[self.messageAry sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
希望有效,
NSString *res =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//Sorting an array
NSMutableArray *sortArray = [res valueForKey:@"Year"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
yearArray = [sortArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
在Swift 3.0版本中
let sortedCapitalArray = yourArray.sorted {($0 as AnyObject).localizedCaseInsensitiveCompare(($1 as AnyObject)as! String) == ComparisonResult.orderedAscending}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.