我目前正在对另一位同事编写的代码进行故障排除,该代码使用以下代码出现越界错误。它涉及在 UINavigatorController 中选择一个项目。它还涉及 coreData 的使用。
代码看起来像这样(出于故障排除和清晰目的,一些代码已被删除)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// : so far no errors with these lines of code. indexPath returns [0,0] or [0,1];
NSLog(@" : *** DetailViewController/didSelectRowAtIndexPath() - executing method ...");
NSLog(@" : *** DetailViewController/didSelectRowAtIndexPath() - indexPath = %@",indexPath);
// : returns row number (as an integer)
NSLog(@": *** DetailViewController/didSelectRowAtIndexPath() indexPath.row = %d",indexPath.row);
// : managedObject returns coreData information.
// Directory *managedObject = (Directory *)[finalArray objectAtIndex:indexPath.row];
// NSLog(@": *** DetailViewController/didSelectRowAtIndexPath() managedObject = %@",managedObject);
// example return
/*
<Directory: 0x5919e50> (entity: Directory; id: 0x59195d0 <x-coredata://FE8A3A0C-A0E4-4E0E-A90D-8471227D2284/Directory/p3> ; data: {
ID = 48;
IsFile = 0;
LastChanged = "2011-01-04 14:39:00 +0000";
Name = "All Papers by Author";
ParentID = 7;
Type = pdf;
}
*/
// : returns the ID value from the managed object
self.num = [managedObject ID];
NSLog(@": *** DetailViewController/didSelectRowAtIndexPath() self.num (managedObject.ID) = %@",[managedObject ID]);
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:finalArray];
// : finalArray has two elements when this method runs
NSLog(@"eja: DetailViewController/didSelectRowAtIndexPath() finalArray length is %i",[finalArray count]);
[self.finalArray removeAllObjects]; // releases the objects, but makes the array empty;
// : finalArray after remove all objects runs
NSLog(@"eja: DetailViewController/didSelectRowAtIndexPath() finalArray length is %i",[finalArray count]);
// ** THE OUT OF BOUNDS ERROR OCCURS HERE **
[self.finalArray setArray:[self searchDatabase:[self.num intValue] withPredicate:@"ParentID"]];**
// NSLog(@": DetailViewController/didSelectRowAtIndexPath() finalArray is %@",self.finalArray);
// ... more code here, but not relevant.
// : release the temp NSMutable array
[tempArray release];
// : maybe release the finalArray?
}
当我调试应用程序时,我相信 finalArray 应该被清除(removeAllObjects)并且应该被重新填充,但是我得到了一个越界错误
由于未捕获的异常“NSRangeException”而终止应用程序,原因:“ * -[NSMutableArray objectAtIndex:]: index 1 beyond bounds for empty array”
不确定错误来自哪里,所以寻找一些建议和提示......
编辑:我在 removeAllObjects 语句之后添加了一个新的跟踪语句
// : finalArray after remove all objects runs
NSLog(@"eja: DetailViewController/didSelectRowAtIndexPath() finalArray length is %i",[finalArray count]);
它返回的计数为 0。那么我是否应该怀疑因为它的长度为零,它没有空间重新分配内存来添加新项目?我认为这就是可变数组的工作方式(或多或少)。
编辑2:代替setArray,我还尝试添加ObjectsFromArray,替换它:
[self.finalArray setArray:[self searchDatabase:[self.num intValue] withPredicate:@"ParentID"]];**
// 有了这个
[self.finalArray addObjectsFromArray:[self searchDatabase:[self.num intValue] withPredicate:@"ParentID"]];
但我返回了类似的错误(超出范围)......