iPad应用程序的didSelectRowAtIndexPath中的NSRangeException

时间:2013-04-04 19:00:13

标签: xcode ipad uitableview

使用基于点击另一个表格中的单元格来填充表格的应用程序。所以,我点击(名为)食谱,并填充第二个表(成分)。我正在使用核心数据从sqlite数据库中提取数据。当我选择第一个食谱时,成分就没有问题了。选择任何其他配方会导致NSRangeException错误 代码:

- (void)tableView:(UITableView*)aTableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath

{

UITableViewCell *cell = (UITableViewCell *)[(UITableView *)srcTableView cellForRowAtIndexPath:indexPath];
NSLog(@"didSelectRowAtIndexPath: row=%i",indexPath.row);

MealPlanItAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Ingredients" inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDesc];
NSLog(@"Cell: %@", cell.textLabel.text);
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(RecipeID = %@)", cell.textLabel.text];

[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;


NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) 
{
    NSLog(@"No matches");
    dtlData = [[NSMutableArray alloc] initWithArray:nil];
    [dtlTableView reloadData];
} else {

    NSLog(@"Match found");
    dtlData = [[NSMutableArray alloc] initWithArray:nil];
    [dtlTableView reloadData];
    matches = [objects objectAtIndex:0];
    for(matches in objects)
    {
        [dtlData insertObject:[matches valueForKey:@"Ingredient"] atIndex:indexPath.row];
        [dtlTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [dtlTableView reloadData];

    }

}
[request release];

}

它在接近尾声的线上爆炸:     [dtlData insertObject:[匹配valueForKey:@“Ingredient”] atIndex:indexPath.row]; 出现错误: *由于未捕获的异常'NSRangeException'而终止应用程序,原因:'* - [__ NSArrayM insertObject:atIndex:]:索引4超出空数组的边界' 索引4是单击的第4个单元格...因此它始终与单元格行对应。

使用NSLog,调用返回数据并返回到具有适当计数的“对象”。 并且,就像我说的,它在单击第一个单元格但没有其他单元格时有效。我可以在第一个单元格上多次单击并继续工作。所以,它与0指数(我怀疑)有关,但无法弄清楚是什么。 如果我更换行

[dtlData insertObject:[matches valueForKey:@"Ingredient"] atIndex:indexPath.row];

[dtlData insertObject:[matches valueForKey:@"Ingredient"] atIndex:0];

我得到完全相同的行为。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

UITable View Code没有任何问题(因为我快速查看了一下,只是想知道为什么要在每次点击表视图单元格时分配数组?初始化数组一次,并处理添加或删除对象适当地)。无论如何,提出你的问题:问题是由于使用 [array insertobject:] 原因是数组是由NILL对象初始化的,当你尝试在索引n处插入对象时,它会抱怨数组为空,因为索引< n 都是NIL。因此,我建议您只需调用[array addobject:],而不是使用[array insertobject:atindex:],这将在连续的位置添加对象并解决崩溃问题。