Search code examples
iosobjective-csortingxml-parsingnsarray

Sort array based on data


I have a tableview that displays data from an array stored in a NSObject. One of the properties in the NSObject is inputtime (currentCall.inputtime) and I want to sort my displayed data based on that. How would I go about doing this? Thanks.

Here is my 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;
}

Solution

  • What you should do is instead of sorting the cells in cellForRow, you should be sorting your array ahead of time and then calling [tableview reloadData].

    There are many ways to sort your array, and without knowing all of the information about your object one way to sort by date is as follows.

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