I have two UIViewControllersin my application (in relation to this question).
Each of them has NSFetchedResultsControllera request for the same entity, called News. Both of them have the same sort descriptors, and they use the same subclass UITableViewCellto display everything. They also match NSFetchedResultsControllerDelegateand run delegate methods.
The only difference is that the first view controller, I will call it SummaryVC, displays only the first (up to) 6 objects. While the other, NewsFeedVCshows all the objects, and also loads more objects. Because of this, delegate methods in SummaryVCjust run[self.tableView reloadData];
When you first start the application, it displays SummaryVCand starts loading the first 6 Newsobjects (converted from JSON) and saves them in the BG stream.
Then it FRCtakes a save and displays the objects.
But...
With interruptions (I hate this word) after clicking and popping up between different parts of the application. I will return to SummaryVC, and the application will fail.
It is always the same mistake.
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. *** -[_PFArray objectAtIndex:]: index (46) beyond bounds (6) with userInfo (null)
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[_PFArray objectAtIndex:]: index (46) beyond bounds (6)'
In this case, more than 6 objects were loaded into Core Data. 6 raises suspicion of FRCbelonging SummaryVC.
I tried a few things to fix this.
- Set the delegate
FRCto nil on viewWillDisappear. - Set
FRCto zero on viewWillDisappear. - When delegate methods invoke validation on
VCthe actual VCscreen. NewsFeedVC viewWillDisappear .
, saveContext FRC. , NewsFeedVC , VC , , , , .
, . .
FRC...
- (NSFetchedResultsController *)fetchedResultsController
{
if (!_fetchedResultsController) {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"News"];
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSSortDescriptor *sourceSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"source" ascending:YES];
NSSortDescriptor *titleSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
fetchRequest.sortDescriptors = @[dateSortDescriptor, sourceSortDescriptor, titleSortDescriptor];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.moc sectionNameKeyPath:nil cacheName:@"AllNewsItems"];
_fetchedResultsController.delegate = self;
NSError *error = nil;
[_fetchedResultsController performFetch:&error];
if (error) {
NSLog(@"Error performing fetch: %@, %@", error, [error userInfo]);
}
}
return _fetchedResultsController;
}
, , FRC . , . ?
, ,?
EDIT2
, - , .
EDIT3
, . , NewsFeedVC, , , SummaryVC.