我的内部有UITableView
和UICollectionView
。我想把它排序为Descend(最新帖子优先)。我怎么想这样做?,我尝试了几种方法,但都没有用。
以下是我的代码和回复
[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];
答案 0 :(得分:2)
_annArray实际上是一个NSDictionary,带有键" 2017年9月"," 2017年8月"等等......就我所见,每个键的值就是一个包含单个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块解析为一个对象,并对类型进行类型检查和排序会更好。