2013-04-04 15 views
0

使用基於單擊另一個表中的單元格填充表的應用程序。所以,我點擊(表名爲)配方,第二個表(配料)填充。我使用核心數據從sqlite數據庫中提取數據。當我選擇第一個配方時,配料沒有問題。選擇任何其他配方會導致出現NSRangeException錯誤。
代碼:用於iPad的didSelectRowAtIndexPath中的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:@ 「成分」] atIndex:indexPath 。行]; ,錯誤代碼:*由於未捕獲的異常'NSRangeException',原因:'* - [__ NSArrayM insertObject:atIndex:]:索引4超出空數組的邊界' 索引4是第4個單元格點擊。因此它總是與單元格行對應。

使用NSLog,數據被調用返回並返回到具有適當計數的「對象」。 而且,正如我所說的,它在點擊第一個單元但沒有其他單元時起作用。我可以在第一個單元格上多次點擊,並繼續工作。所以,它與0指數(我懷疑)有關,但不能確定什麼。 如果我更換線

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

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

我得到完全相同的行爲。

有什麼想法?

回答

0

UITable查看代碼沒什麼問題(因爲我有一個快速瀏覽,只是想知道爲什麼你每次點擊表視圖單元格時分配數組?初始化數組一次,並處理添加或刪除適當的對象)。無論如何,來到你的問題:問題是由於使用 [array insertobject:] 原因是該數組由NILL對象初始化,當您嘗試在索引n插入對象時,它投訴數組爲空作爲索引< n都是零。所以不是使用[array insertobject:atindex:],我建議你只需調用[array addobject:]這將在連續的位置添加對象並解決崩潰問題。