我使用JSON从SQL数据库中获取数据。 数据包括一天(周一至周日)和任务。 如果我想将每天的所有任务分组,我该怎么做呢?
我正在查看tableview方法中的NumberOfSections,但我似乎无法弄明白。 一周只有7天所以我知道我必须返回7个部分,但是如何在正确的一周内输入正确的数据呢? 谁能让我走上正轨? 这就是我获取数据的方式:
- (void)retrieveData {
//Pass the username to a string so we can use it further
DataManager* dm = [DataManager sharedInstance];
NSString *leefgroep = (NSString*)[dm objectForKey:@"leefgroep"];
NSLog(@"%@",leefgroep);
NSString *strURL = [NSString stringWithFormat:@"http://myurl.php?leefgroep=%@&",leefgroep];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
jsonArray = [NSJSONSerialization JSONObjectWithData:dataURL options:
kNilOptions error:nil];
//setup Array
todoArray =[[NSMutableArray alloc] init];
//loop through jsonArray
for (int i = 0; i < jsonArray.count; i++)
{
//create objects
NSString * cID =[[jsonArray objectAtIndex:i]objectForKey:@"id"];
NSString * cDay=[[jsonArray objectAtIndex:i]objectForKey:@"day"];
NSString * cHour=[[jsonArray objectAtIndex:i]objectForKey:@"hour"];
NSString * cTask=[[jsonArray objectAtIndex:i]objectForKey:@"task"];
//add object to Array
[todoArray addObject:[[Todo alloc]initWithday:cDay andID:cID andhour:cHour andtask:cTask]];
}
[self.tableView reloadData];
}
返回的JSON数据如下:
{"id":"1753","day":"3","hour":"08:00:00","task":"go to the shop"},{"id":"1755","day":"4","hour":"08:00:00","task":"change tires"}
提前致谢
Dresse
答案 0 :(得分:0)
如果您可以将完整数据作为对象列表获取,那将是很棒的,其中每个对象包含当天的任务列表。然后,您可以将主列表的元素计数作为节计数返回,并将每个子列表的元素计数作为行计数返回。
{
[
{
day : "Sun",
tasks : [{task1}, {task2}]
},
{
day : "Mon",
task : [{task1}, {task2}, {task3}]
}
.
.
.
.
]
}
答案 1 :(得分:0)
如果没有对您发布的代码进行任何修改,您可以将数据拆分为表视图数据源方法中的部分,如下所示:
- (NSInteger)numberOfRowsInSection:(NSInteger)section {
NSUInteger rows = 0;
for (Todo *todo in todoArray) {
if (todo.day == section) rows++;
}
return rows;
}
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Todo *cellTodo = nil;
NSUInteger row = 0;
for (Todo *todo in todoArray) {
if (todo.day == indexPath.section) {
if (row == indexPath.row) {
cellTodo = todo;
break;
}
row++;
}
}
// Construct your UITableViewCell with the data held in cellTodo.
}
有更好的方法来安排您的数据,但如果不知道数据的完整列表使用方案,则很难选择最佳数据。这个需要对现有代码进行最少的更改。