Search code examples
objective-ciosjsonuitableviewsections

iOS UITableView: Custom sections using information from a JSON object, not just counting it


Say I have this JSON:

[
    {"x":"01", "ID":"1"},
    {"x":"02", "ID":"2"},
    {"x":"02", "ID":"3"},
    {"x":"03", "ID":"4"},
    {"x":"03", "ID":"5"},
    {"x":"03", "ID":"6"},
    {"x":"03", "ID":"7"}
]

and I want to create a UITableView like this:

------------
Section 01
------------
ID: 1
------------
Section 02
------------
ID: 2
ID: 3
------------
Section 03
------------
ID: 4
ID: 5
ID: 6
ID: 7

How can I find out how many sections I need and how do I output the correct data in each section?


Solution

  • Ended up with this solution:

        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        for(NSDictionary* dict in data) {
            NSNumber *x = [dict objectForKey:@"x"];
            NSMutableArray *resultsForX = [result objectForKey:x];
    
            if(!resultsForX) {
                resultsForX = [NSMutableArray array];
                [result setObject:resultsForX forKey:x];
            }
    
            [resultsForX addObject:dict];
        }
    
        NSMutableArray *newArr = [result allValues];