Ios Xcode-将JSON数据分组到节中
我使用JSON从SQL数据库获取数据。 数据包括一天(周一至周日)和任务。 如果我想将每天的所有任务分为几个部分,我该怎么做呢 我现在正在查看tableview方法中的NumberOfSections,但似乎无法理解它。 一周只有7天,所以我知道我必须返回7个部分,但如何在一周的正确日期下放置正确的数据? 谁能让我走上正轨? 以下是我获取数据的方式:Ios Xcode-将JSON数据分组到节中,ios,json,xcode,Ios,Json,Xcode,我使用JSON从SQL数据库获取数据。 数据包括一天(周一至周日)和任务。 如果我想将每天的所有任务分为几个部分,我该怎么做呢 我现在正在查看tableview方法中的NumberOfSections,但似乎无法理解它。 一周只有7天,所以我知道我必须返回7个部分,但如何在一周的正确日期下放置正确的数据? 谁能让我走上正轨? 以下是我获取数据的方式: - (void)retrieveData { //Pass the username to a string so we can use it f
- (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];
提前谢谢
Dresse如果您可以获取完整的数据作为对象列表,其中每个对象都包含当天以及当天的任务列表,那就太好了。然后,您可以将主列表的元素计数返回为节计数,将每个子列表的元素计数返回为行计数
{
[
{
day : "Sun",
tasks : [{task1}, {task2}]
},
{
day : "Mon",
task : [{task1}, {task2}, {task3}]
}
.
.
.
.
]
}
不需要对发布的代码进行任何修改,就可以在表视图数据源方法中将数据拆分为多个部分,如下所示:
- (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.
}
有更好的方法来安排数据,但如果不知道数据的完整列表使用场景,就很难选择最佳方法。这需要对现有代码进行最少的更改。如果您提供一些代码来描述如何从数据库中加载数据以及在哪个结构中检索数据,则会更容易为您提供帮助。你好,Ian,我发布了一些代码。我使用一种将对象添加到数组的方法。我还发布了在Web服务器上看到的JSON输出。在我的cellforRowAtIndexPath中,我可以简单地将值放在tableview单元格中。但我似乎不知道如何对他们进行分组。
- (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.
}