如何在iPhone上按升序对NSMutableArray进行排序?

3

我有一个SQLite数据库(DB),并将其转换为模型类,然后将DB的数据存入NSMutableArray中。我的DB类似于以下内容。 学生姓名 | 注册号码 | 入学日期 我已成功在UITableView中显示了入学日期,但我想在UITableView中按升序和降序对入学日期进行排序。 非常感谢您的帮助!

5个回答

18
你可以使用 NSSortDescriptorsortUsingDescriptors:sortDescriptors 来对可变数组进行排序。
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DatesOfJoin" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];

这应该是“sortedArrayUsingDescriptors”。 - Pochi
1
不确定数组是否为可变数组。https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html - unexpectedvalue

4

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;
}];

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];

希望能够正常工作,

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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接