【问题标题】:NSRangeException in didSelectRowAtIndexPath for iPad appiPad 应用程序的 didSelectRowAtIndexPath 中的 NSRangeException
【发布时间】:2013-03-27 00:26:25
【问题描述】:

开发基于单击另一个表格中的单元格来填充表格的应用程序。因此,我单击(名为)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:[匹配 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];

我得到了完全相同的行为。

有什么想法吗?

【问题讨论】:

    标签: xcode ipad uitableview


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多