Секционированный UITable & JSON
В течение нескольких дней я пытался выяснить, как проанализировать этот JSON в секционированном UITable, но у меня ничего не получилось, я только смог выяснить, как получить имя секции, но не смог получить количество строк и данные каждой секции для каждой строки в каждом разделе.
Так как транспортная группа может время от времени меняться, и их имя может меняться, поэтому я думаю, что мне нужно использовать allKeys, чтобы сначала найти заголовок каждого раздела.
Пожалуйста, помогите и указывает мне правильное направление для извлечения данных для секционного UITable, спасибо.
{
"transport" : {
"public" : [
{
"transport_id" : "2",
"transport_name" : "Ferry"
},
{
"transport_id" : "3",
"transport_name" : "Bus"
},
{
"transport_id" : "4",
"transport_name" : "Taxi"
},
{
"transport_id" : "5",
"transport_name" : "Tram"
}
],
"Private" : [
{
"transport_id" : "11",
"transport_name" : "Bicycle"
},
{
"transport_id" : "12",
"transport_name" : "Private Car"
}
],
"Misc" : [
{
"transport_id" : "6",
"transport_name" : "By Foot"
},
{
"transport_id" : "7",
"transport_name" : "Helicopter"
},
{
"transport_id" : "8",
"transport_name" : "Yatch"
}
]
}
}
NSDictionary *results = [jsonString JSONValue];
NSDictionary *all = [results objectForKey:@"transport"];
NSArray *allKeys = [all allKeys];
NSArray *transports = [results objectForKey:@"transport"];
for (NSDictionary *transport in transports)
{
[transportSectionTitle addObject:(transport)];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [transportSectionTitle count];
}
3 ответа
Самое простое решение, чтобы объяснить это использовать all
словарь как ваш источник данных.
NSDictionary *results = [jsonString JSONValue];
NSDictionary *all = [results objectForKey:@"transport"];
// self.datasource would be a NSDictionary retained property
self.datasource = all;
Затем, чтобы получить количество разделов, которые вы можете сделать:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.datasource count]; // You can use count on a NSDictionary
}
Чтобы получить название разделов:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *title = [[self.datasource allKeys] objectAtIndex:section];
return title;
}
Чтобы получить количество строк в каждом разделе:
- (NSInteger)tableView:(UITableView *)favTableView numberOfRowsInSection:(NSInteger)section {
// Get the all the transports
NSArray *allTransports = [self.datasource allValues];
// Get the array of transports for the wanted section
NSArray *sectionTransports = [allTransports objectAtIndex:section];
return [sectionTransports count];
}
Затем, чтобы получить строки:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Get the all the transports
NSArray *allTransports = [self.datasource allValues];
// Get the array of transports for the wanted section
NSArray *sectionTransports = [allTransports objectAtIndex:indexPath.section];
// Then get the transport for the row
NSDictionary *transport = [sectionTransports objectAtIndex:indexPath.row];
// Now you can get the name and id of the transport
NSString *tansportName = [transport objectForKey:@"transport_name"];
NSString *transportId = [transport objectForKey:@"transport_id"];
NSString *transportDescription = [NSString stringWithFormat:@"%@ - %@",transportId, transportName];
cell.textLabel.text = transportDescription;
return cell;
}
В этом вся суть.
Вы можете хранить allKeys
а также allValues
Массивы как свойства класса вместо того, чтобы проходить через них во всех методах делегата и источника данных табличного представления, но теперь у вас должна быть вся информация для создания таблицы.
Надеюсь это поможет:)
Ключом к тому, что вам нужно сделать, является признание того, что после того, как ваша строка JSON будет проанализирована в объекте, она станет серией вложенных NSArrays и NSDictionarys, и вам просто нужно соответствующим образом просмотреть значения
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[transports allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [(NSArray*)[transports objectForKey:[[transports allKeys] objectAtIndex:section]] count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [transports allKeys];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// get transport category (e.g."public")
NSString *transportCategory = (NSString*)[[transports allKeys] objectAtIndex:[indexPath section]];
// get transport items belonging to the category
NSArray *items = (NSArray*)[transports objectForKey:transportCategory];
// get transport item for this row
NSDictionary *transportItem = [items objectAtIndex:[indexPath row]];
// extract values of transport item
NSString *transportName = [transportItem objectForKey:@"transport_name"];
NSString *transportID = [transportItem objectForKey:@"transport_id"];
cell.textLabel.text = transportName;
return cell;
}
NSDictionary *results = [jsonString JSONValue];
NSDictionary *allTypes = [results objectForKey:@"transport"];
NSArray *allTransportKeys = [allTypes allKeys];
Количество секций:
NSInteger numberOfSections = [allKeys count];
Количество рядов в разделе:
NSString *key = [allKeys objectAtIndex:section];
NSArray *array = [allTypes objectForKey:key];
NSInteger numberOfRows = [array count];
Данные в indexPath:
NSString *key = [allKeys objectAtIndex:indexPath.section];
NSArray *array = [allTypes objectForKey:key];
NSDictionary *itemDict = [array objectAtIndex:indexPath.row];
Затем вы можете извлечь данные из itemDict.