I have an UITableViewController which is backed by an NSFetchedResultsController.
My NSFetchedResultsController put results into two sections based on a boolean.
In a background thread, the datasource is altered such that rows are added or removed.
I have my background thread's NSManagedObjectContext's merging correctly and this situation work fine for most cases. Rows alter when the data is changed and move between sections with animations.
There is one situation however where my application crashes with an EXC_BAD_ACCESS.
The case is when the last row in a section is moved to the other section. (Stack trace below). The crash occurs in objc_msgSend but the normal debugging tips I use aren't returning anything helpful, I simply receive "Value can't be converted to integer" from gdb.
The NSFetchedResultsControllerDelegate methods get called in the following order:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller;
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type;
// ^ The parameters specify a deletion of the 1st section
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath;
// ^ The parameters specify a moved row from the 1st section to the 1st section
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller;
Looking through StackOverflow, many of the people who encounter similar issues are backing their UITableViewController manually using an NSArray or NSMutableArray and they're simply not updating the datasource at the correct time. In this case the NSFetchedResultsController is handling returning the number of rows and sections and is definitely updated by the time the [tableView endUpdates] is called.
Has anyone got any debugging tips, pointers or solutions?
This blog post hints at working around a similar problem where a new section is created.
I have two options if I cannot solve this issue as is:
Forgo animation on rows and simply call [tableView reloadData]
Switch to using NSArray backed storage for the UITableView and hope for the best
Update
I have modified the Apple sample Core Data application "Locations" to use an NSFetchedResultsController directly and reproduced the issue.
I have uploaded the source code for this project. Use that project to reproduce the issue.
Simply click the + button a few times and wait
Every 5 seconds an item gets moved to another category.
When the first category is about to be emptied, it crashes.
The crash is sometimes about creating two animations for the same cell as per other StackOverflow questions on the topic. More commonly the crash is as discussed above and below.
Reference
The stack trace:
#0 0x31e0afbc in objc_msgSend ()
#1 0x32c11522 in -[_UITableViewUpdateSupport(Private) _computeRowUpdates] ()
#2 0x32c10510 in -[_UITableViewUpdateSupport initWithTableView:updateItems:oldRowData:newRowData:oldRowRange:newRowRange:context:] ()
#3 0x32c0f99e in -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] ()
#4 0x32c0e66c in -[UITableView endUpdatesWithContext:] ()
#5 0x000088d6 in -[DraftHistoryController controllerDidChangeContent:] (self=0x3f6f1e0, _cmd=0x377ca29c, controller=0x3f716e0) at /Users/ataylor/Documents/Documents/Programming/iPhone/Drafter/Drafter/Drafter/DraftHistoryController.m:323
#6 0x3775a892 in -[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] ()
My NSFetchedResultsControllerDelegate methods are the same ones from the Apple sample code:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Reloading the section inserts a new row and ensures that titles are updated appropriately.
[tableView reloadSections:[NSIndexSet indexSetWithIndex:newIndexPath.section] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates]; // <---- Crash occurs here
}
The relevant UITableViewControllerDelegate methods are as follows:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
I took a quick look. Your modified Locations project didn't crash on me but it did generate core data exceptions. The problem lies in reloading the sections in controller:didChangeObject:. I changed the code as follows and everything looks good to me (including the section titles) on both iOS 4.3 and iOS 5.
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
// other cases here
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
I was super curious about the code that fixed an issue with adding a new section so I decided to pop it in place of my current NSFetchedResultsControllerDelegate methods and it indeed solved my problem. Tracing through, I have discovered that this code from the Apple "Locations" sample crashes when using the NSFetchedResultsController:
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Reloading the section inserts a new row and ensures that titles are updated appropriately.
[tableView reloadSections:[NSIndexSet indexSetWithIndex:newIndexPath.section] withRowAnimation:UITableViewRowAnimationFade];
break;
But the following code works perfectly:
case NSFetchedResultsChangeMove:
if (newIndexPath != nil) {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths: [NSArray arrayWithObject:newIndexPath] withRowAnimation: UITableViewRowAnimationTop];
}
else {
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:[indexPath section]] withRowAnimation:UITableViewRowAnimationFade];
}
break;
I don't have a case where section headings will change, I won't continue debugging to solve the issue Apple's code purports to fix around section titles.
Because every question needs a swift answer, here's one (based on XJones's accepted answer). As is the case with the other answers, the magic is in the .Move: delete and insert instead of moving the row.
This is my NSFRC delegate didChangeObject:
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Delete:
if let deletePath = indexPath {
self.tableView.deleteRowsAtIndexPaths([deletePath], withRowAnimation: .None)
}
break
case .Insert:
if let insertPath = newIndexPath {
self.tableView.insertRowsAtIndexPaths([insertPath], withRowAnimation: .Fade)
}
break
case .Update:
if let updatePath = indexPath {
self.tableView.reloadRowsAtIndexPaths([updatePath], withRowAnimation: .None)
}
break
case .Move:
if let indexPath = indexPath, newIndexPath = newIndexPath {
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
}
break
}
}
I was getting a crash overtime I deleted the last row in a section.
Do make sure you have implemented controller:didChangeSection:atIndex:forChangeType: to handle section removal.
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.viewTable insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.viewTable deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
Related
I have created a class 'ToDoListTableViewController' with superclass 'UITableViewController' and have tried implementing this piece of code
[self configureCell:((ToDoTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath]) atIndexPath:indexPath];
but I am getting the error that is in the title of this question. This is the full method in which it is in
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
switch (type) {
case NSFetchedResultsChangeInsert:
{
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeDelete:
{
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeUpdate:
{
[self configureCell:((ToDoTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath]) atIndexPath:indexPath];
break;
}
case NSFetchedResultsChangeMove:
{
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
and this is the beginning of the implementation file
#import "ToDoListTableViewController.h"
#import <CoreData/CoreData.h>
#import "ToDoTableViewCell.h"
#interface ToDoListTableViewController ()<NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#end
#implementation ToDoListTableViewController
in code I have found online this method is supposed to work but I am getting this error, can someone help me please?
You have to create the method configureCell:atIndexPath: before using it!. If you are following an online tutorial maybe you forgot to create it. Usually people create this method to isolate the setting of the cell properties from the rest of the creation of the cell itself. For example for the case when you try to calculate the height of the cell based on its contents using autolayout.
In my app I have NSFetchedResultsController which update my table in every change in the DB.
Sometime during change something went wrong in the app and the table remain empty no matter what I do (even if I change screen and return, the table remain empty).
Only after turn off the app and turn it back on everything seems to be fine again.
I isolate the problem to this error
"CoreData: error: Serious application error. An exception was caught
from the delegate of NSFetchedResultsController during a call to
-controllerDidChangeContent:. Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section
after the update (19) must be equal to the number of rows contained in
that section before the update (19), plus or minus the number of rows
inserted or deleted from that section (3 inserted, 0 deleted) and plus
or minus the number of rows moved into or out of that section (0 moved
in, 0 moved out). with userInfo (null)"
It seems to be related to an un explain difference between the row number in "begin update" and "end update",which mean something when wrong when deleting or inserting rows.
This is kind of hard to debug using break point because in happens not very often.
Any suggestions?
my code :
#pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.guiTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.guiTableView beginUpdates];
[self.guiTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.guiTableView endUpdates];
break;
case NSFetchedResultsChangeDelete:
[self.guiTableView beginUpdates];
[self.guiTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationLeft];
[self.guiTableView endUpdates];
// if (controller.sections.count==0) {
// [self alertAboutNothingInMyAssetsAndPop];
// }
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.guiTableView;
SOOptionCell *cell;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
break;
case NSFetchedResultsChangeUpdate:
cell = (SOOptionCell *)[tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath animated:YES];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
[self.guiTableView endUpdates];
}
First, remove all of your -beginUpdates and -endUpdates calls inside of the delegate methods. There should only be one of each. One -beginUpdates in the -controllerWillChangeContent: and one -endUpdates in the -controllerDidChangeContent:. I would go so far as to say that you should change the other methods back to the examples provided by Apple instead of writing them yourself.
Once you do that does the discrepancy go away? I suspect it will.
I'm getting a crash when trying to access an object in NSFetchedResultsController.
2013-11-10 15:15:06.568 Social[11503:70b] CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. *** -[__NSArrayI objectAtIndex:]: index 2 beyond bounds for empty array with userInfo (null)
2013-11-10 15:15:06.570 Social[11503:70b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 2 beyond bounds for empty array'
viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
self.resultController = [DataEngine sharedInstance].postsFetchedResultController;
self.resultController.delegate = self;
[self.resultController performFetch:nil];
[self.tableView reloadData];
[[DataEngine sharedInstance] fetchInBackground];
}
Result Controller Delegate
#pragma mark - NSFetchedResultsControllerDelegate Methods -
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
switch (type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeMove:
[self.tableView moveRowAtIndexPath:indexPath toIndexPath:newIndexPath];
break;
default:
break;
}
}
table view
#pragma mark - UITableView Delegate & Datasrouce -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.resultController.fetchedObjects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self cellForRowAtIndexPath:indexPath];
}
One reason for crash on below line could be that you are updating self.resultContrlller after you have used it for retuning the number of rows of your table section. Make sure that if you are constantly updating your self.resultContrlller object then you take a copy of it and then use for your table drawing.
// This code does not prevent crash. Changing your regular code to modern objective-C way
Post *post = [self.resultContrlller fetchedObjects][indexPath.row];
The data source should not change while table is reloading itself. You should use a copy of fetchedObjects instead to load the table. So, evey time, before you reload your table, take a copy [[self.resultContrlller fetchedObjects] copy] and the use it for table drawing. Your main source can then keep on changing. And after table reload is done with copy you may want to reload it it again if there was a change in the data. Such crashes happens when your data source changes faster than table reloads.
In one of my NSManagedObject subclasses I had the follwiing code which was causing the issue. NSSets are automatically initialized on NSManagedObejcts and there is no need to initialize them.
- (void)awakeFromFetch
{
if (!self.comments)
self.comments = [NSMutableSet set];
if (!self.medias)
self.medias = [NSMutableSet set];
}
Another problem was that during insert indexPath is null, I had to use newIndexPath instead
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:#[newIndexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
break;
I have a UITableView that uses an NSFetchedResultsController as data source.
The core data store is updated in multiple background threads running in parallel (each thread using it's own NSManagedObjectContext).
The main thread observes the NSManagedObjectContextDidSaveNotification
notification and updates it's context with mergeChangesFromContextDidSaveNotification:.
Sometimes it happens that the NSFetchedResultsController sends an
NSFetchedResultsChangeUpdate event with an indexPath that does not exist
anymore at that point.
For example: The result set of the fetched results controller contains
1 section with 4 objects. The first object is deleted in one thread.
The last object is updated in a different thread. Then sometimes the
following happens:
controllerWillChangeContent: is called.
controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: is called with
type = NSFetchedResultsChangeDelete, indexPath.row = 0.
controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: is called with
type = NSFetchedResultsChangeUpdate, indexPath.row = 3.
But the fetched results controller contains only 3 objects now, and if call
MyManagedObject *obj = [controller objectAtIndexPath:indexPath]
to update the table view cell according to the NSFetchedResultsChangeUpdate
event, this crashes with a NSRangeException exception.
Thank you for any help or ideas!
I have now found a solution for my problem. In the case of an update event, there is no need to call
[self.controller objectAtIndexPath:indexPath]
because the updated object is already supplied as the anObject parameter to the -controller:didChangedObject:... delegate.
I have therefore replaced -configureCell:atIndexPath: by a -configureCell:withObject: method that uses the updated object directly. This seems to work without problems.
The code looks now like this:
- (void)configureCell:(UITableViewCell *)cell withObject:(MyManagedObject *)myObj
{
cell.textLabel.text = myObj.name;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCellIdentifier"];
[self configureCell:cell withObject:[self.controller objectAtIndexPath:indexPath]];
return cell;
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
/* ... */
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] withObject:anObject];
break;
/* ... */
}
}
This is actually quite common because of the bug in Apple's boiler plate code for NSFetchedResultsControllerDelegate, which you get when you create a new master/detail project with Core Data enabled:
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath]
atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
Solution #1: Use anObject
Why query the fetched results controller and risk using an incorrect index path when the object is already given to you? Martin R recommends this solution as well.
Simply change the helper method configureCell:atIndexPath: from taking an index path to take in the actual object that was modified:
- (void)configureCell:(UITableViewCell *)cell withObject:(NSManagedObject *)object {
cell.textLabel.text = [[object valueForKey:#"timeStamp"] description];
}
In cell for row, use:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
[self configureCell:cell withObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
return cell;
}
Finally, in the update use:
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath]
withObject:anObject];
break;
Solution #2: Use newIndexPath
As of iOS 7.1, both indexPath and newIndexPath are passed in when a NSFetchedResultsChangeUpdate happens.
Simply keep the default implementation's usage of indexPath when calling cellForRowAtIndexPath, but change the second index path that is sent in to newIndexPath:
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath]
atIndexPath:newIndexPath];
break;
Solution #3: Reload rows at index path
Ole Begemann's solution is to reload the index paths. Replace the call to configure cell with a call to reload rows:
case NSFetchedResultsChangeUpdate:
[tableView reloadRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
break;
There are two disadvantages with this method:
By calling reload rows, it will call cellForRow, which in turn calls dequeueReusableCellWithIdentifier, which will reuse an existing cell, possibly getting rid of important state (e.g. if the cell is in the middle of being dragged a la Mailbox style).
It will incorrectly try and reload a cell that isn't visible. In Apple's original code, cellForRowAtIndexPath: will return "nil if the cell is not visible or indexPath is out of range." Therefore it would be more correct to check with indexPathsForVisibleRows before calling reload rows.
Reproducing the bug
Create a new master/detail project with core data in Xcode 6.4.
Add a title attribute to the core data event object.
Populate the table with several records (e.g. in viewDidLoad run this code)
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
for (NSInteger i = 0; i < 5; i++) {
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
[newManagedObject setValue:[#(i) stringValue] forKey:#"title"];
}
[context save:nil];
Change configure cell to show the title attribute:
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%# - %#", [object valueForKey:#"timeStamp"], [object valueForKey:#"title"]];
}
In addition to adding a record when the new button is tapped, update the last item (Note: this can be done before or after the item is created, but make sure to do it before save is called!):
// update the last item
NSArray *objects = [self.fetchedResultsController fetchedObjects];
NSManagedObject *lastObject = [objects lastObject];
[lastObject setValue:#"updated" forKey:#"title"];
Run the app. You should see five items.
Tap the new button. You will see that a new item is added to the top, and that the last item does not have the text "updated," even though it should have had it. If you force the cell to reload (e.g. by scrolling the cell off the screen), it will have the text "updated."
Now implement one of the three solutions outlined above and in addition to an item being added, the last item's text will change to "updated."
I'm trying to implement a AQGridView that uses a fetched results controller as its datasource.
I'm not particular sure how to handle the NSFetchedResultsController delegate methods using the grid view; namely the content changing ones. I understand how to use the FRC for the other grid view datasource delegates.
Could somebody point me in the right direction?
The result should look a little something like this:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[gridView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
break;
case NSFetchedResultsChangeDelete:
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
ChannelPageViewController *currentPageController, *destinationPageController;
NSIndexSet * indices = [[NSIndexSet alloc] initWithIndex: indexPath.row];
NSIndexSet *newIndices = [[NSIndexSet alloc] initWithIndex:newIndexPath.row];
switch(type) {
case NSFetchedResultsChangeInsert:
[gridView insertItemsAtIndices:newIndices withAnimation:AQGridViewItemAnimationNone];
break;
case NSFetchedResultsChangeDelete:
[gridView deleteItemsAtIndices:indices withAnimation:AQGridViewItemAnimationNone];
break;
case NSFetchedResultsChangeUpdate:
[gridView reloadItemsAtIndices:indices withAnimation:AQGridViewItemAnimationNone];
break;
case NSFetchedResultsChangeMove:
[gridView deleteItemsAtIndices:indices withAnimation:AQGridViewItemAnimationNone];
[gridView insertItemsAtIndices:newIndices withAnimation:AQGridViewItemAnimationNone];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[gridView endUpdates];
if ([[frc fetchedObjects] count] == 1) {
[gridView reloadData];
}
}
Since AQGridView doesn't have sections, the best way to handle it would be to implement the NSFethcedresultscontroller delegate methods, and ignore any code for the cases related to updated sections. Also make sure you initialize the fetchrequest with no sectionNameKeyPath.
Then just follow the normal pattern for updating rows, but using NSIndexSet instead of NSIndexPath and InsertItemAtIndicies/DeleteItemAtIndicies instead of insertRowAtIndexPath/deleteRowAtIndexPath
I'm moving my AQGridView to CoreData now, so I'll post any updates to my answer as soon as I'm done...
When the content changes I do a
[self.gridView reloadData];
or something like that in your case. It is exactly the same as with a tableview.