我有一个SQLite数据库(DB),并将其转换为模型类,然后将DB的数据存入NSMutableArray中。我的DB类似于以下内容。 学生姓名 | 注册号码 | 入学日期 我已成功在UITableView中显示了入学日期,但我想在UITableView中按升序和降序对入学日期进行排序。 非常感谢您的帮助!
我有一个SQLite数据库(DB),并将其转换为模型类,然后将DB的数据存入NSMutableArray中。我的DB类似于以下内容。 学生姓名 | 注册号码 | 入学日期 我已成功在UITableView中显示了入学日期,但我想在UITableView中按升序和降序对入学日期进行排序。 非常感谢您的帮助!
NSSortDescriptor
和 sortUsingDescriptors:sortDescriptors
来对可变数组进行排序。NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DatesOfJoin" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];
- (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;
}];
升序排列:
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}