我有SQLite数据库(DB)并将其作为模型类并在NSMutableArray中获取数据库。我的DB与此DB类似。 StudentName | RegisterNumber | DatesOfJoin(DOJ) 我在tableView中成功显示了DoJ,但我想在tableView中按升序和降序排序DatesOfJoin。 任何帮助将不胜感激,并提前感谢您。
答案 0 :(得分:18)
您可以使用NSSortDescriptor
和sortUsingDescriptors:sortDescriptors
对可变数组进行排序。
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DatesOfJoin" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];
答案 1 :(得分:4)
你有很多方法可以对数组进行排序:
- (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
答案 2 :(得分:3)
对于降序:
NSArray *sorted = [Arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] < [obj2 intValue]) return NSOrderedDescending;
else return NSOrderedAscending;
}];
升序:
NSArray *sorted = [Arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
else return NSOrderedDescending;
}];
答案 3 :(得分:1)
您可以尝试使用:
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];
希望有效,
答案 4 :(得分:0)
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}