0

使用基于单击另一个表格中的单元格来填充表格的应用程序。因此,我单击(名为)Recipe 的表,然后填充了第二个表(Ingredients)。我正在使用核心数据从 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:[matches valueForKey:@"Ingredient"] atIndex:indexPath.row]; 出现错误:* 由于未捕获的异常 'NSRangeException' 导致应用程序终止,原因:'* -[__NSArrayM insertObject:atIndex:]: index 4 beyond bounds for empty array' 其中索引 4 是单击的第 4 个单元格......所以它始终与单元格行相对应。

使用 NSLog,数据由调用返回并返回到具有适当计数的“对象”中。而且,就像我说的那样,它在单击第一个单元格但没有其他单元格时有效。我可以在第一个单元格上单击多次,它会继续工作。所以,它与 0 索引有关(我怀疑)但不知道是什么。如果我更换线路

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

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

我得到完全相同的行为。

有什么想法吗?

4

1 回答 1

0

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

于 2013-06-29T16:08:16.720 回答