0

Hi everyone I'm working with a JSON file to populate a UITableView.

The JSON file has two fields that I need to use:

- "First name" - "region"

The "region" fields must be assigned for the creation of the UITableView sections.

The "name" fields must be sorted according to the section.

JSON File :

{
  "Università" : [
     {
      "nome" : "Università degli Studi di Trento",
      "regione" : "Trentino Alto Adige"
    },
     {
      "nome" : "Università per Stranieri di Reggio Calabria \"Dante Alighieri\"",
      "regione" : "Calabria"
    },
     {
      "nome" : "Università degli Studi Suor Orsola Benincasa",
      "regione" : "Campania"
    },
     {
      "nome" : "Università degli Studi della Calabria ",
      "regione" : "Calabria"
    },
     {
      "nome" : "Università degli Studi di Napoli \"L'Orientale\"",
      "regione" : "Campania"
    }
  ]
}

As you can see from the JSON file, each "name" has a "region" so they must be sorted that way for example

(section) region 1
(cell) name with region 1
(cell) name with region 1
(cell) name with region 1

(section) region 2
(cell) name with region 2
(cell) name with region 2
(cell) name with region 2

How can I implement this to populate my UITableView?

This is the implementation I have done so far

-(void)retrieveUniversityListFromJSONFile {

    /* Interpelliamo il file JSON all'interno del progetto per ottenere i nomi di tutte le università attualmente presenti nel file */

    // Nome del file JSON
    NSString *JSONFileName = @"university";
    NSString *path = [[NSBundle mainBundle] pathForResource:JSONFileName ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];

    // Creazione di un dizionario che eredita informazioni dal file JSON
    NSDictionary *JSONDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    // Inizializziamo l'array per prepararla ad accogliere i dati
    _universityList = NSMutableArray.new;

    for (NSDictionary *dict in JSONDict[@"Università"]) {

        // Otteniamo i nomi delle università presenti nel file
        NSString *universityName = dict[@"nome"];

        // Otteniamo i nomi delle regioni italiane
        NSString *regionName = dict[@"regione"];

        // Aggiungiamo i risultati per le regioni all'array || _regionList ||
        [_regionList addObject:regionName];

        // Aggiungiamo i risultati all'array || _universityList||
        [_universityList addObject:universityName];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _regionList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _universityList.count;
}
kAiN
  • 2,559
  • 1
  • 26
  • 54
  • Your university list is being populated by all the regions universities combined. You need an individual array for each region. – Milo Oct 05 '19 at 18:34

1 Answers1

0

You need to manipulate the JSON data into an array that can be referenced by the table view's index path. The structure could be an array of dictionaries with each dictionary holding the region, and the list of names associated. You would need to iterate the JSON data and build a new array of dictionaries, adding one for each new region encountered, then adding the name to the array of names in that region's dictionary. Your index path section and row would reference the dictionary and index of the names respectively.

Your function might look like this:

_regionList = [NSMutableArray array];

for (NSDictionary *dict in JSONDict[@"Università"]) {

    // Otteniamo i nomi delle università presenti nel file
    NSString *universityName = dict[@"nome"];

    // Otteniamo i nomi delle regioni italiane
    NSString *regionName = dict[@"regione"];

    BOOL found = NO;
    for (NSDictionary *regDict in _regionList) {
        if ([regDict[@"region_name"] isEqualToString:regionName]) {
             //Region exists already
             found = YES;

             if (regDict[@"names"] == nil) {
                 //name array does not exist, create new array
                 regDict[@"names"] = [NSMutableArray arrayWithObject:universityName];
             } else {
                 //name array does exist
                 regDict[@"names"] addObject:universityName];
             }

             break;
    }

    if (found == NO) {
       //Region does not exist, create new region dictionary
       NSMutableDictionary *newRegionDict = [NSMutableDictionary new];
       newRegionDict[@"region_name"] = regionName;
       newRegionDict[@"names"] = [NSMutableArray arrayWithObject:universityName];
    }
}

Example of above data structure:

[ 
  [0]: { "region_name": "Calabria",
         "names": [ 
                   [0]: "Università per Stranieri di Reggio Calabria \"Dante Alighieri\"",
                   [1]: "Università degli Studi della Calabria"
                  ]
       },
  [1]: { "region_name": "Campania",
         "names": [ 
                   [0]: "Università degli Studi di Napoli \"L'Orientale\"",
                   [1]: "Università degli Studi Suor Orsola Benincasa"
                  ]
       }
]


The number of rows in section would be [_regionList[section][@"names"] count];

Your -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section might look like this:

...
NSDictionary *region = _regionList[section];
NSString *regionName = _regionList[@"region_name"];

return regionName;

Your -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath:

...
NSDictionary *region = _regionList[indexPath.section];
NSString *uniName = _regionList[@"names"][indexPath.row];
...

Don't forget to call [yourTableView reloadData] after manipulating data referenced by the table.

Milo
  • 5,041
  • 7
  • 33
  • 59
  • Hello sorry for the delay in my answer. So I'm trying to implement your suggestion but I can't understand why you call the "region" key instead of "region_name". I modified my JSON file as you suggested but to this dot the "region" key is no longer listed. This is how I implemented my JSON file { "Università" : [ [0]: { "regione": "Abruzzo", "nome": [ [0]: "Università degli Studi \"Gabriele d'Annunzio\"", ] "latitudine": [ [0]: 42.368174 ] "longitudine": [ [0]: 14.14877 ] ] }, ] } – kAiN Oct 09 '19 at 15:36
  • can you help me understand this better? – kAiN Oct 09 '19 at 15:59