Question

I am using a table view in such look like a excel sheet type can say multiple columns. Add a pan gesture on column header to increase the width of column as in excel sheet. I am facing problem in sorting the column data. Column data always sort as a alphabet/string format. while I have some number type columns as well date type. So all columns are sorted as a string. Could you please suggest some option to make this happen. I am having all data in a array as a dictionary from web service.

Let me share some code for sorting.

-(void)sortTableDataUsingSortKey:(NSString *)sortKey withAscending:(BOOL)isAscending {

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending selector:@selector(compare:)];

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    NSArray *arrTemp = [[NSArray alloc] initWithArray:[data_array sortedArrayUsingDescriptors:sortDescriptors]];
    [data_array count]?[data_array removeAllObjects]:NSLog(@"Datsource Table Not null");
    [data_array addObjectsFromArray:arrTemp];
    arrTemp = nil;

    [_table_view reloadData];
}
Was it helpful?

Solution

I fixed the issue. I just added conditional sort descriptor method as per the data type of dictionary. And in Data_array dictionary where data going to added.Add data in proper data type. like if data is numbers then added these in dictionary as a number / float or NSDate.

Now I check the the type of data coming in dictionary as per sorting column. And change the sorting selector (Compare for non string data and for string data used caseInsensitiveCompare:) And rest works fine.

Final mothod that works is now as ..

-(void)sortTableDataUsingSortKey:(NSString *)sortKey withAscending:(BOOL)isAscending {
    NSSortDescriptor *sortDescriptor = nil;

    if ([data_array count] && [[[data_array objectAtIndex:0] valueForKey:sortKey] isKindOfClass:[NSString class]]) {
            sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending selector:@selector(caseInsensitiveCompare:)];
        }
        else {
            sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending selector:@selector(compare:)];
        }

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    NSArray *arrTemp = [[NSArray alloc] initWithArray:[data_array sortedArrayUsingDescriptors:sortDescriptors]];
    [data_array count]?[data_array removeAllObjects]:NSLog(@"Datsource Table Not null");
    [data_array addObjectsFromArray:arrTemp];
    arrTemp = nil;

    [_table_view reloadData];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top