使用基于单击另一个表格中的单元格来填充表格的应用程序。因此,我单击(名为)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];
我得到完全相同的行为。
有什么想法吗?