0

我有两个视图控制器。一个是 searchResults 表视图控制器 (VC1),用户在其中看到与选择条件匹配的行列表;另一个是 ViewDetail (表视图控制器) (VC2),用户在其中看到 VC1 所选行的详细信息。通过设置 VC2 的相关属性,获取所选行的详细信息所需的信息以及 managedContext 引用在 VC1 的 prepareforsegue 方法中从 VC1 传递到 VC2。在我的测试过程中,每次在 VC1 上选择不同的行以查看不同项目的详细信息时,我都会在(使用导航控制器后退按钮)VC1 和 VC2 之间切换。这可以正常工作 7-15 次切换,但在尝试切换后突然崩溃。我已尽我所能对此进行了调查,但没有解决方案就陷入困境,因此发布了这个。请帮忙。错误是一个特定的数组超出了索引 0 的范围。虽然我理解,但我不希望这个由获取请求的结果填充的数组为空。因此,我怀疑托管上下文有问题。提供了来自 VC2 的代码片段

//All this is in  ViewDidLoad of VC2 App crashes at the last line of this snippet. trying to get an object at index 0 which is non existent but should not be ...
NSFetchRequest *request  = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" cameraid ==  %@",(NSNumber *)self.selectedCameraid];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Cameras"
                                          inManagedObjectContext:self.managedContext];

//Configure core data request
[request setEntity:entity];
[request setPredicate:predicate];

//Execute request
NSError *error = nil;

NSMutableArray *mutableFetchResults =  [[self.managedContext executeFetchRequest:request error:&error] mutableCopy];

if (mutableFetchResults == nil) {
    // Handle the error.
    NSLog(@"Some error in fetching results");

}
NSLog(@"Mutable fetch results data %@",mutableFetchResults);
self.resultsArray = mutableFetchResults;
Cameras *rowdata = [self.resultsArray objectAtIndex:0]; //Cameras is a managed object
4

1 回答 1

0

After a bit of further digging I found the issue... I am type casting a string as NSNumber (NSNumber *)self.selectedCameraid in the above code. Apparently this is what has been causing the crash. I converted the NSString object to a NSNumber object using NSNumberformatter and everything seems to work fine. I realised it is not safe to type cast objects in this manner.

于 2013-01-03T20:05:31.440 回答