Reputation: 715
I´m working on an iOS application that is going to list some data that I stored in a NSDictionary. I will use a table view to do this, but having some problem how I should start.
The data looks something like this:
category = (
{
description = (
{
id = 1;
name = Apple;
},
{
id = 5;
name = Pear;
},
{
id = 12;
name = Orange;
}
);
id = 2;
name = Fruits;
},
{
description = (
{
id = 4;
name = Milk;
},
{
id = 7;
name = Tea;
}
);
id = 5;
name = Drinks;
}
);
I´m trying to put all the "category" values as a section in the table and the the "name" from each "description" in the correct section. As I mentioned, not sure how to start here, how do I get a new section for every "category"?
Upvotes: 0
Views: 1459
Reputation: 539805
You "just have to" implement the table view datasource methods to extract the information from your dictionary :-)
If self.dict
is the above dictionary, then self.dict[@"category"]
is an array containing
one dictionary per section. Therefore (using the "modern Objective-C subscripting syntax"):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.dict[@"category"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return self.dict[@"category"][section][@"name"];
}
For each section,
self.dict[@"category"][section][@"description"]
is an array containing one dictionary per row. Therefore:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dict[@"category"][section][@"description"] 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];
}
NSString *name = self.dict[@"category"][indexPath.section][@"description"][indexPath.row][@"name"];
cell.textLabel.text = name;
return cell;
}
Upvotes: 2