У меня есть ответ на мою проблему сейчас, я не знаю, правильный ли это подход, но он работает и приветствовал бы комментарии.
Просто чтобы уточнить, в чем была проблема, и что я пытался сделать.
У меня есть базовая сущность данных company
с примерно 10 или около того полями внутри них, однако вместо того, чтобы перечислять их все сразу, я хотел сгруппировать выведенные поля.
Например, у меня есть около 6 полей, относящихся к наличным деньгам, таким как «cash», «marketingBudget», «seoBudget» и т. Д., И я хотел сгруппировать эти данные в tableView, но проблема заключалась в том, что я не знал, как установить отношения так, чтобы table.field.x принадлежал group.x и т. д.
Я пришел к ответу, что использовал PLIST / словарь, который в значительной степени отражает структуру основного объекта данных; и назначьте структуру для групп, которые я хочу отобразить.
Мой словарь выглядит так:
(корень)
-> CompanyTpl (массив)
-> Item 0 (Dictionary)
---> Section (String) = "General"
---> Дети (Массив
)
------> Элемент 0 (словарь)
----------> Key = "name"
----------> Значение = "Название компании" ...
Где Key
будет ссылкой на базовые данные для использования и отображения их содержимого, если это необходимо.
Где Value
будет отображаться в cellForRowAtIndexPath.
Итак, в моем коде я в основном прошел раздел (под которым я имею в виду раздел tableView) и затем нашел соответствующую информацию о детях из PLIST; и получите Ключ / Значение и используйте его по мере необходимости.
Вот сокращенная версия кода.
- (void)viewDidLoad {
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"CompanyTpl" ofType:@"plist"];
self.companyDictionary = [[NSDictionary dictionaryWithContentsOfFile:plistPath] retain];
// self.tableDataSource is a NSMutableArray
self.tableDataSource = [self.companyDictionary objectForKey:@"CompanyTpl"];
// Debugging info
NSLog(@"Section = 0");
NSLog(@"%@", [self.tableDataSource objectAtIndex:0]);
NSLog(@"Section Name = %@", [[self.tableDataSource objectAtIndex:0] objectForKey:@"Section"]);
NSArray *sectionChildren = [[self.tableDataSource objectAtIndex:0] objectForKey:@"Data"];
NSLog(@"Section Children = %@", sectionChildren);
NSLog(@"Count of Section Children = %d", [sectionChildren count]);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return ([self.tableDataSource count]);
}
// Section header
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *title = nil;
title = [[self.tableDataSource objectAtIndex:section] objectForKey:@"Section"];
return title;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = 0;
NSArray *sectionChildren = [[self.tableDataSource objectAtIndex:section] objectForKey:@"Data"];
NSLog(@"Section Children = %@", sectionChildren);
NSLog(@"Count of Section Children = %d", [sectionChildren count]);
rows = [sectionChildren count];
return rows;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *sectionChildren = [[self.tableDataSource objectAtIndex:indexPath.section] objectForKey:@"Data"];
NSDictionary *sectionChildrenData = [sectionChildren objectAtIndex:indexPath.row];
//NSLog(@"Section Children data = %@", sectionChildrenData);
NSString *scKey = [sectionChildrenData objectForKey:@"Key"];
NSString *scValue = [sectionChildrenData objectForKey:@"Value"];
NSLog(@"scKey = %@", scKey);
// Grab the data from Core Data using the scKey
static NSString *CellIdentifier = @"defaultCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
//cell.textLabel.text = @"test";
cell.textLabel.text = scValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
Идея состоит в том, что я могу использовать KEY при обращении к Базовым данным, чтобы захватить их содержимое и отобразить его на контроллере tableView со значением cellForRowAtIndexPath cell.textLabel.text.
Можно пойти немного глубже и получить больше информации в PLIST, например, какими должны быть субтитры и т. Д.
В любом случае, приветствуются комментарии и мысли.
Спасибо.