如何使用dynamicjson数据设置numberOfSectionsInTableView,titleForHeaderInSection

我有一些JSON数据给出下面,我想显示在一个表部分标题是部门,devise,雇员,发展,雇员。

我在numberOfSectionsInTableViewtitleForHeaderInSection使用静态数据,但我想要使用dynamic数据。

我怎样才能做到这一点?

 { "Departments":[ { "name":"Designing", "id":"1.1", "Employees":[ { "name":"Ramesh", "id":"1.1.1", "salary":"4lakhs" }, { "name":"Suresh", "id":"1.1.2", "salary":"4lakhs" } ] }, { "name":"Developing", "id":"1.2", "Employees":[ { "name":"Ram", "id":"1.2.1", "salary":"4lakhs" }, { "name":"Sam", "id":"1.2.2", "salary":"4lakhs" } ] } } 

首先你必须从你指定的stringJSON对象中创build一个NSDictionary。

  NSDictionary *myDict = [NSJSONSerialization JSONObjectWithData:webData options:nil error:NULL]; 

然后在表视图中委托方法:

  - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [[myDict valueForKey:@"Departments"] count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[[[myDict valueForKey:@"Departments"] objectAtIndex:section] valueForKey:@"Employees"] count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [[[myDict valueForKey:@"Departments"] objectAtIndex:section] valueForKey:@"name"]; } 

或者至less我会尝试像这样设置它们。