将升序数组的最后4个对象放入UITableView

时间:2014-03-03 18:33:06

标签: objective-c arrays uitableview

我的数组(旅行)增长取决于用户创建的条目数量。目前,数组是从数据库中按升序排列的。

我需要从最后一个对象开始,并使用数组中最后4个'trip'对象填充我的tableview。

我的tableview只显示4行,我希望这些行是数组中的最后4行。

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if ([trips count] < 4){
    return [trips count]
    } else {
    return 4;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyReuseIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:MyIdentifier];
    }

    UserMiles *cellInfo = [self milesAtIndex:indexPath.row];

    cell.textLabel.text = [NSString stringWithFormat:@"%@ to %@", cellInfo.beg_school, cellInfo.end_school];


    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    dateFormat.dateFormat = @"MM/dd/yyyy";
    NSString *date = [dateFormat stringFromDate:cellInfo.driven_date];

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", date];

    return cell;
}

-(UserMiles *) milesAtIndex: (NSInteger) index
{
    return [trips objectAtIndex:index];
}

2 个答案:

答案 0 :(得分:0)

我使用了reverseObjectEnumerator类(我根本不知道存在!)来完成它。

现在效果很好!

trips = [[trips reverseObjectEnumerator] allObjects];

答案 1 :(得分:0)

您可以使用NSSortDescriptor将数组转换为所需的顺序。最快的解决方法是将您的milesAtIndex:更改为:

-(UserMiles *) milesAtIndex: (NSInteger) index
{
    NSSortDescriptor *sort = [[NSSortDescriptor sortDescriptorWithKey:@"propertyHere" ascending:NO];
    return [[trips sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]] objectAtIndex:index];
}

请注意,@"propertyHere"可以是您要排序的UserMiles对象的任何属性。因此,如果您使用日期,则可能会有myUserMiles.tripDate属性,因此您将@"propertyHere"替换为@"tripDate"