Search code examples
iossortingtableviewrowssections

Xcode UITableView sections and rows sorted by date (from mutableArray)


In my UITableView i have multiple secions with date titles. the dates are sorted by date in a NSMutableArray. my sections are showing the correct dates, that works fine, and the numberofrowsinnsection works fine too. For the cells textlabels I got NSMutableArrays that are sorted in the same order like the sorted dates. How do I get the correct textlabel for the corresponding date(section)? With indexpath.section it works only when there is 1 row in a section. When i got 2 or more rows in a section the textlabels have wrong values. i understand that this could be done with dictionaries, but i couldn´t find a solution.

@property NSMutableArray *dateArray;     //date for my sections
@property NSMutableArray *hoursArray;   //hours for cells textlabel




my sections

"January 2014",
"April 2014",
"June 2014"

my hours:

"1",
"2",
"3",

///////////EDIT

When i use Cell.textlabel.text =[hoursarray objectatindex:indexpath.row] It always starts at index 0 in every section.

When i use Cell.textlabel.text =[hoursarray objectatindex:indexpath.section] It has the correct sorting when there is only 1 row each section. But when there are more rows in a section, the order is wrong


Solution

  • You have to create your datasource sorted so just create a sectionArray of rowArray and then use it accordingly. Then you can use it like this:

    Cell.textlabel.text = [[sectionArray objectatindex:indexpath.section] objectAtIndex:indexpath.row];
    

    Now you just need to manage your datasource aacordingly.

    UPDATED: You can create 2D array like this

    NSMutableArray *dateArray = [[NSMutableArray alloc] init];
    
    
    for(int i=0; i<=dateData.length; i++)
    {
       NSMutableArray *hoursArray = [[NSMutableArray alloc] init];
    
       for(int j=0; j<=hoursData.length; j++)
       {
         [hoursArray addObject:yourObject];
       }
    
       [dateArray addObject:hoursArray];
    }
    

    This is just an example, however you can optimize according to your need.