根据数据对数组进行排序

时间:2012-12-13 18:51:25

标签: ios objective-c sorting xml-parsing nsarray

我有一个tableview,显示存储在NSObject中的数组中的数据。 NSObject中的一个属性是inputtime(currentCall.inputtime),我想根据它对我显示的数据进行排序。我该怎么做呢?感谢。

这是我的cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JointCAD *currentCall = [[xmlParser calls] objectAtIndex:indexPath.row];
    static NSString *cellidentifier1 = @"cell1";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier1];

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

    cell.textLabel.text = currentCall.currentCallType;
    cell.detailTextLabel.text = currentCall.location;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

2 个答案:

答案 0 :(得分:6)

你应该做的不是在cellForRow中对单元格进行排序,而是应该提前对数组进行排序,然后调用[tableview reloadData]

有许多方法可以对数组进行排序,并且在不知道有关对象的所有信息的情况下,按日期排序的方法如下:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"inputtime" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

答案 1 :(得分:1)

您必须先对数据模式进行排序。但在方法didSelectRowforIndexPath之外。

您访问的代码中的某些位置:

currentCall = [[xmlParser calls] objectAtIndex

此时必须已对数组进行排序。

ViewWillAppear中进行排序。 在cellForRowAtIndexPath中,必须对数据进行排序。

如果数据模式动态变化,例如通过删除单元格行,您必须使用[self.tableView reloadData]

重新设置表格数据