我有一个NSDictionary,其中包含多个字典:
{
complete = 0;
description = Description;
"due_date" = "2014-02-28 16:30:03";
name = Task;
priority = 2;
"task_id" = 1;
"user_id" = 1;
},
{
complete = 0;
description = "";
"due_date" = "0000-00-00 00:00:00";
name = "";
priority = 0;
"task_id" = 2;
"user_id" = 1;
}
我想在我的UITableView
中显示“name”的每个实例我试过这个:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
for (task in tasks) {
cell.textLabel.text = [[task objectAtIndex:indexPath.row] valueForKey:@"name"];
}
return cell;
}
但每次尝试运行时,应用程序都会崩溃。
我做错了什么?
这是我得到的错误:
断言失败 - [UITableView _configureCellForDisplay:forIndexPath:]
答案 0 :(得分:3)
将您的代码更改为:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell.textLabel.text = [[tasks objectAtIndex:indexPath.row] valueForKey:@"name"];
return cell;
}
问题是task
是字典,所以它没有回复objectAtIndex:
。
顺便说一句,您还需要创建或出列UITableViewCell
个实例,但我只是为您纠正了崩溃问题。
答案 1 :(得分:1)
您遇到崩溃的原因是您从nil
返回tableView:cellForRowAtIndexPath:
。
我认为您也误解了此表视图数据源方法的工作原理。它会在表中的每个表格单元格中调用一次(因此,为什么要从中返回UITableViewCell
...)。您不需要在其中循环数据集合 - 您应该根据indexPath从集合中获取正确的数据对象。
最重要的是,正如其他人所说,如果tasks
实际上是NSDictionary
,则它不会回复objectAtIndex
。很可能,您可能希望您的数据收集是NSArray
,如果它还没有。
编辑:
根据您收到的错误判断,tasks
实际上是NSArray
(因为错误是由nil
返回tableView:cellForRowAtIndexPath:
引起的)。请尝试以下方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellIdentifier" forIndexPath:indexPath];
NSDictionary *task = [tasks objectAtIndex:indexPath.row];
cell.textLabel.text = [task objectForKey:@"name"];
return cell;
}
编辑2:
此外,您应该使用objectForKey:
代替valueForKey:
。
答案 2 :(得分:0)
您无法在字典上调用objectAtIndex:
方法,这就是您的应用崩溃的原因。相反,您需要使用objectForKey:
和相应的键来获取所需的值。
答案 3 :(得分:0)
尝试将这些NSDictionary存储在NSArray中。 NSArray允许您保存它们,同时使用“objectAtIndex”访问对象。
如果需要在运行时添加NSDictionary,请尝试使用NSMutableArray,它允许您在需要时添加和删除数组对象。