【问题标题】:How to sort an array by id or month: Descending (Latest Post First)?如何按 id 或月份对数组进行排序:降序(最新帖子优先)?
【发布时间】:2017-10-17 12:47:41
【问题描述】:

我有一个UITableView 和一个UICollectionView 里面。我想将其排序为 Descend (Latest Post First)。我该怎么做?,我尝试了几种方法,但都不起作用。

以下是我的代码和回复

  [Utilities serverRequest:@{@"getAnnouncement":@"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {

    collectionViewDic[@"announcement"] = response[@"response"];
   _annArray = response[@"response"];
   NSLog(@"AnnouncementResponse%@",response);

    // sorting to newest
   /*
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"anc_id" ascending:NO];
    NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor];
    [_annArray sortedArrayUsingDescriptors:sortDescriptors];
     NSLog(@"Sorted - AnnouncementResponse%@",response);
     */
    /*
    NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"anc_id" ascending:NO];
    NSArray* sortedArray = [_annArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    NSLog(@"Sorted Array Response -%@",sortedArray);
    */
    announcmentDone = YES;
    if (newsDone && bulletInDone && announcmentDone && !refreshed) {
        refreshed = YES;
        [table reloadData];
    }
} errorBlock:nil];

【问题讨论】:

  • 请根据我的回复建议我一个代码..

标签: ios objective-c uitableview sorting uicollectionview


【解决方案1】:

_annArray 实际上是一个 NSDictionary,键为“September 2017”、“August 2017”等...据我所知,每个键的值都是一个数组,其中包含一个 NSDictionary。要获取您需要的所有值,例如:

    NSArray *responseValues = [response[@"response"] allValues]; // An NSArray of NSArrays
    NSMutableArray *dictionarys = [NSMutableArray new];
    for (NSArray *dictArrays in responseValues) {
        for (NSDictionary *dict in dictArrays) {
            [dictionarys addObject:dict];
        }
    }
    _annArray = dictionarys;

然后您应该能够按预期进行排序:

  NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"anc_id" ascending:NO];
  NSArray* sortedArray = [_annArray sortedArrayUsingDescriptors:@[sortDescriptor]];
  NSLog(@"Sorted Array Response -%@", sortedArray);

不过,这是一种快速而粗略的方法。实际上,最好将每个 JSON 块解析为一个对象,并对对象进行类型检查和排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 2021-12-29
    • 2014-02-16
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多