iOS数组排序 请求后,数组元素的排序 时间戳,最热,点赞数等

[ZOYSessionManager dataWithUrlString:GetVideoDataComment andParameter:@{@"id":userID,@"pageNo":@1,@"pageSize":@20}  SucessBlock:^(id data) {

//        NSDictionary * dic = [(NSData *)data  objectFromJSONData];

self->_mode=[CommunityModel mj_objectWithKeyValues:data];

NSLog(@"mode%@",self->_mode);

for (self->_itemmodel in self->_mode.content) {

[self.accountArray addObject:self->_itemmodel];

NSMutableArray *timeArr = [[NSMutableArray alloc]init];

NSMutableDictionary *dateKeyArr = [[NSMutableDictionary alloc]init];

for(CommunitItemModel *acc in _accountArray) {

// 时间戳转成时间对象用于排序

int timer = [acc.date intValue];

NSDate  *date = [NSDate dateWithTimeIntervalSince1970:timer];

[timeArr addObject:date];

// 时间戳转成时间戳字符串作为key,制作哈希表

NSNumber *dataNum = [NSNumber numberWithLongLong:timer];

NSString *datekey = [dataNum stringValue];

[dateKeyArr setObject:acc forKey:datekey];

}

// 3.将时间NSDate数组排序

NSArray *orderedDateArray = [timeArr sortedArrayUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {

// 降序排序,最近的时间靠前

return [date2 compare:date1];

}];

// 4.根据排序好的时间数组对号入座将对象按时间排序

// 临时数组,保存排序后的对象数组

NSMutableArray *sortedAccounts = [[NSMutableArray alloc]init];

NSDate *datekey = [[NSDate alloc]init];

for (int i = 0; i<orderedDateArray.count; i++) {

datekey = orderedDateArray[i];

// 日期对象转换成时间戳字符串key

NSString *datekeys = [NSString stringWithFormat:@"%lld", (long long)[datekey timeIntervalSince1970]];

// 根据时间戳字符串key取对应的对象(哈希表)

[sortedAccounts addObject:[dateKeyArr objectForKey:datekeys]];

}

// 5.更新排序后的对象数组[ARC中不需要手动释放排序前的数组]

_accountArray = sortedAccounts;

self.dataArray = _accountArray;

//            [self.dataArray addObject:self->_itemmodel];

[self.myTableView reloadData];

}

//                NSLog(@"dataArray%@",self.dataArray);

[self.myTableView reloadData];

} failureBlock:^(NSError *error) {

NSLog(@"error  is  %@",error);

}];

NSLog(@"userID%@,@1,@20",userID);

self.myTableView.estimatedRowHeight = 80.0f;

self.myTableView.rowHeight = UITableViewAutomaticDimension;

//    [self.myTableView reloadData];

}

整合后的小demohttps://github.com/ZOYOOPlus/TimeSortDemo

上一篇:数组Array.sort()排序的方法


下一篇:js中删除数组元素的几种方法