以下是我的情况:
我有一个应用程序,可以在我的应用程序的初始视图中加载Core Data中的表。让我们称之为View1TVC。 AppDelegate.m已设置好,因此View1TVC是初始视图。
现在在View2TVC中,我正在尝试加载SAME TABLE(在View1TVC中过滤)但应用程序崩溃时出现以下错误:
由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:'一个实例 NSFetchedResultsController需要一个非零的fetchRequest和 managedObjectContext
与为View1TVC和View2TVC加载表格相关的代码完全相同!它适用于View1TVC,但不适用于View2TVC。这是View2TVC代码:
-(void)setupFetchedResultsController
{
NSString *entityName = @"Task";
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// REQUEST:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// SORT:
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor
sortDescriptorWithKey:@"name"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// FETCH:
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
Task *task = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = task.name;
return cell;
}
当应用程序转移到View2TVC并到达setupFetchedResultsController方法的SORT行时,应用程序会挂起:
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
任何人都有任何想法?该错误是否与我将View1TVC识别为AppDelegate.m中的默认应用程序有关?这是AppDelegate.m中的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
View1TVC *controller = (View1TVC *)navigationController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
return YES;
}
我非常感谢任何人都可以借出的洞察力!感谢。