簡體   English   中英

如何按升序排序NSMutableArray,iPhone?

[英]How to sort NSMutableArray in ascending order, iPhone?

我有SQLite數據庫(DB)並將其作為模型類並在NSMutableArray中獲取數據庫。 我的DB與此DB類似。 學生名稱| RegisterNumber | DatesOfJoin(DoJ)我在tableView中成功顯示了DoJ,但我想在tableView中按升序和降序排序DatesOfJoin。 任何幫助將不勝感激,並提前感謝您。

您可以使用NSSortDescriptorsortUsingDescriptors: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM