Question thats been bugging me here:
Are NSFetchedResultsController "controllerDidChangeContent" etc delegate methods supposed to be called when initially fetching content or only when that initially fetched content is updated / changed?
Having an issue where even though the initial fetch comes back with the results, the delegate methods are not called unless that initial results batch changes (from a network request later on for example).
This means i currently need to force a collection view update with a reloadData() since waiting for the delegate methods to call fails when there is only existing content in core data and nothing new changing it.
I have confirmed that at the time the initial fetch completes, the delegate is set and the results are valid. Any gotchas i'm missing here?
The delegate methods are only called for changes made after performFetch: has been called. You can infer this from several statements in the class reference documentation.
Related
This is very weird situtaion of using NSFetchedResultsController with core data in iOS development by Swift.
At first, FetchedResultsController contains only info of non-changed sections but no changed section info, althought that change causes controllerDidChangeContent method call tableView.reloadData method and in turn invoke numberOfSections method.
But subsequent manual invokes, e.g. in viewWillAppear, of the FetchedResultsController results in correct showing of the changed section info along with other non-changed section info.
In other words, fetched change of an attribute referred in sectionNameKeyPath via cloudkit in a background context was saved to viewContext which in turn saved it to persistent container. During the process, controllerDidChangeContent was invoked and tableView.reloadData was called. At that moment, in numberOfSections, no changed section info can be observed in the fetchedResultsController.sections, which only contains info of non-changed sections. I have set that attribute name as first sort descriptor in the fetch request associated with the fetchedResultsController.
I can't really find any clue of the illogical; any thought is welcome.
Issue found!!! Credit giving to Michael in answering the NSFetchedResultsController calls didChangeObject delete instead of update
Cause is my predicate using string interpolation for number value. After changing the use of number predicate, magic happens. Thanks Stackoverflow community!
I use an NSFetchedResultsController with a stored NSFetchRequest on which I change the predicate.
After changing the predicate I call performFetch on the NSFetchedResultsController, but this does not trigger the usual controllerWillChangeContent ... controllerDidChangeContent callbacks.
So I have to reloadData on my table view to make it up to date.
Is this expected behaviour? Is this documented somewhere? Am I overlooking something?
I don't think it's documented that those methods won't be called in response to performFetch, but the documentation for when they are called does not seem to include that case. The description of performFetch() indicates that
After executing this method, you can access the receiver’s the fetched objects with the property fetchedObjects.
No mention of delegate callbacks. Meanwhile the delegate docs say that the protocol includes
...methods that will be called by the associated fetched results controller when the fetch results have changed.
Which doesn't specifically rule out changing to a different fetch request, but doesn't clearly include it either.
I'm pretty sure what you're seeing is normal. Changing the fetch request doesn't lead to delegate callbacks, but changing data affected by the existing fetch request does cause them.
Here is my context:
When I launch my app I fetch local data from CoreData and fill a tableview with it. At the same time I send an asynchronous request to my webservice to fetch what will be the new content of my tableview.
As soon as the request sends me a response I delete all the instances of the current NSManagedObjects and create new ones with the new data I got. Then I replace the datasource of my tableview to an array of the new NSManagedObjectContexts instances.
My problem:
I'm getting an error : CoreData could not fulfill a fault for ... if I scroll my tableview when the request finished and is triggering the deletion/creation of my tableview's data source.
I understand that this problem occurs because I'm trying to access an old NSManagedObject instance while doesn't exist anymore as it is explained in the doc : Apple doc. But I have no idea of what are the best practices in my case.
I don't want to block the user until my request finished but I have to prevent any error if he accesses "old" data while the request didn't finish (e.g : what if the user taps on a cell and I pass an instance of an NSManagedObject to another viewcontroller but when the request finishes this object doesn't exist anymore ?)
I would appreciate any help !
I highly recommend you to use NSFetchedResultsController since it's sole purpuse is:
You use a fetched results controller to efficiently manage the results returned from a Core Data fetch request to provide data for a UITableView object.
When using a fetched results controller it is much easier to handle the Core Data events like insert, delete, update.
You say you have three sections in your table view? That's no problem, NSFetchedResultsController can handle all of that.
Take a look at this. Apple provides a very nice set of instructions on how to configure and use NSFetchedResultsController.
I am working on a VOIP/Chat application that receives data even while in the background.
I need to disable the NSFetchedResultsController when the app is moving to the background to prevent UI changes in the background.
I do it like this -
- (void)applicationWillResignActive
{
[super applicationWillResignActive];
self.fetchedResultsController.delegate = nil;
}
- (void)applicationDidBecomeActive
{
[super applicationDidBecomeActive];
self.fetchedResultsController.delegate = self.fetchResultControllerDelegate;
}
I have noticed that I don't need to call [self.tableView reloadData] when coming back to foreground. (EDIT : just to clarify the Core Data DB was updated with new data while the app was in the background and the fetchedResultsController.delegate was nil).
And the table updates itself right after reassigning the fetchedResultsController.delegate.
What makes it update, does the fetchedResultsController preforms fetch when reassigned ?
Are there any pitfalls to this approach that can make a conflict between the tableView and the fetchedResultsController ?
Thanks
Fetched results controllers provide the following features:
Optionally monitor changes to objects in the associated managed object context, and report changes in the results set to its delegate (see “The Controller’s Delegate”).
Optionally cache the results of its computation so that if the same data is subsequently re-displayed, the work does not have to be repeated (see “The Cache”).
A controller thus effectively has three modes of operation, determined by whether it has a delegate and whether the cache file name is set.
No tracking: the delegate is set to nil.
The controller simply provides access to the data as it was when the fetch was executed.
Memory-only tracking: the delegate is non-nil and the file cache name is set to nil.
The controller monitors objects in its result set and updates section and ordering information in response to relevant changes.
Full persistent tracking: the delegate and the file cache name are non-nil.
The controller monitors objects in its result set and updates section and ordering information in response to relevant changes. The controller maintains a persistent cache of the results of its computation.
What makes it update, does the fetchedResultsController preforms fetch when reassigned ?
It only does a fetch the first time you create a fetched results controller. After that, it is notified of any change to any object in the database as the changes happen, and evaluates whether to add or remove the object to the list of results. It never does a second fetch (except maybe if you get a low memory warning?).
Fetches are slow, it has to read flash memory and that takes milliseconds. However when an object is being changed, it's in RAM so operations only take nanoseconds. This is why it tries hard not to ever look at the sqlite database.
Are there any pitfalls to this approach that can make a conflict between the tableView and the fetchedResultsController ?
I'm not sure, maybe. If you haven't found any problems in testing, then I think you should assume it's fine. But be sure to test it again carefully when iOS 8 betas are available mid next year, so you can fix any problems before it's released to the public.
If you're worried about RAM usage, you should destroy the fetched results controller. But beware it will take a fairly significant amount of time to create it again, when the user switches back to your app.
My program does work like link below:
Update results of NSFetchedResultsController without a new fetch
show result of NSFetchedResultsController to UITableView
get new object from web service and store it to core data (in same view controller, with RestKit)
update table view with notification of NSFetchedResultsController delegate
The implementation of NSFetchedResultsControllerDelegate is copied from Apple's Core Data project and my predicated is:
[NSPredicate predicateWithFormat:#"isMyTest == TRUE"]
If the property update goes from TRUE to FALSE, it removes rows from the tableview (because the object for the row is in fetchedObjects of the NSFetchedResultsController)
However, if the property update goes from FALSE to TRUE, the NSFetchedResultsController notifies nothing, so the new data cannot be seen in table view. If I update BOTH NSFetchedResulsController and UITableView manually, it shows the new data.
I thought NSFetchedResultController watches all changes in persistent store, is it too big hope? :D
(I really want to do that because other view controller can update persistent store, then it is hard to update the view controller.)
If so, can you let me know how can I update NSFetchedResultsController in beautifully way?
(update)
in reference of NSfetchedResultsController, I read words below:
A controller thus effectively has three modes of operation, determined
by whether it has a delegate and whether the cache file name is set.
No tracking: the delegate is set to nil. The controller simply
provides access to the data as it was when the fetch was executed.
Memory-only tracking: the delegate is non-nil and the file cache name
is set to nil. The controller monitors objects in its result set and
updates section and ordering information in response to relevant
changes.
Full persistent tracking: the delegate and the file cache name are
non-nil. The controller monitors objects in its result set and updates
section and ordering information in response to relevant changes. The
controller maintains a persistent cache of the results of its
computation.
"Full persistent tracking" does not mean what I want? I set up cacheName, but it works same.
I thought NSFetchedResultController watches all changes in persistent
store, is it too big hope?
The FRC only automatically observes the objects returned by its fetch. This is normally not a problem as changes to objects monitored by an FRC should arise from either the tableview UI or a background context. In the former, the FRC is alerted to the change and in the latter, merging the foreground and background context will trigger the FRC to update.
It sounds like you've got code changing values but you're not notifying the FRC that you've made any changes. (If you got a tableview displaying all objects whose isMyTest == TRUE then obviously you can't access objects from the UI whose isMyTest == FALSE.) In that case, you need to register the tableview controller for:
NSManagedObjectContextObjectsDidChangeNotification
… notifications from the context so that you can tell the FRC to update for changes made outside its observation.
I'm sorry to my mistake, I tested with new test project.
CoreData DOES full-tracking of whole persistent store.
This means, if new object that is suitable to predicate of NSFetchedResultsController, delegate will notify it.