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;
}