首先要做的是将该 JSON 转换为 Objective-C 数据结构。我推荐一个数组数组,其中“X”是每个“ID”值数组的索引。
就像是:
NSMutableArray *tableSections;
NSMutableArray *sectionData;
CustomDataObject *yourCustomDataObject;
int sectionIndex;
//Pseudo-code to create data structure
for(data in json) {
sectionIndex = data.X;
yourCustomDataObject = [[CustomDataObject alloc] initWithId:data.ID];
//Do index check first to insure no out of bounds
if(sectionIndex != OutOfBounds)
sectionData = [tableSections objectAtIndex:sectionIndex];
//Create the new section array if there isn't one for the current section
if(!sectionData) {
sectionData = [NSMutableArray new];
[tableSections insertObject: sectionData atIndex: sectionIndex];
[sectionData release];
}
[sectionData addObject: yourCustomDataObject];
[yourCustomDataObject release];
}
上面的代码只是帮助您入门的伪代码。创建这个数组数组可能是您以前已经做过的事情。
重要的部分是通过实现 UITableViewDataSource 协议来访问这些数据。我建议继承 UITableView 并在您的自定义子类中实现 UITableViewDataSource 协议。
您将需要这些方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [tableSections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[tableSections objectAtIndex: section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Implement as you normally would using the data structure you created
NSMutableArray *sectionData = [tableSections objectAtIndex: indexPath.section];
CustomDataObject *dataObject = [sectionData objectAtIndex: indexPath.row];
NSLog(@"\n**** Debug Me *****indexPath: section: %i row: %i \ndataObject%@", indexPath.section, indexPath.row, dataObject);
}
这应该足以让你开始。弄清楚其余的细节应该是一个好习惯。