Is it wrong to use an NSFetchedResultsController
purely for data management, i.e., without using it to feed a UITableView
?
I have a to-many relationship in a Core Data iPhone app. Whenever data in that relationship changes, I need to perform a calculation which requires that data to be sorted. In Apple's standard Department/Employees example, this would be like determining the median salary in a given Department. Whenever an Employee is added to or removed from that Department, or an Employee's salary changes, the median calculation would need to be performed again.
Keeping data sorted and current and getting notifications when it changes sounds like a great job for NSFetchedResultsController
. The only "problem" is that I'm not using a UITableView
. In other words, I'm not displaying sorted Employees in a UITableView
. I just want an up-to-date sorted array of Employees so I can analyze them behind the scenes. (And, of course, I don't want to write a bunch of code that duplicates much of NSFetchedResultsController
.)
Is it a bad idea to use an NSFetchedResultsController
purely for data management, i.e., without using it to feed a UITableView
? I haven't seen this done anywhere, and thought I might be missing something.
I would not call it bad but definitely "heavy".
It would be less memory and CPU to watch for saves via the NSManagedObjectContextDidSaveNotification
and do the calculation there. The notification will come with three NSArray
instances in its userInfo
and you can then use a simple NSPredicate
against those arrays to see if any employee that you care about has changed and respond.
This is part of what the NSFetchedResultsController
does under the covers. However you would be avoiding the other portions of the NSFetchedResultsController
that you don't care about or need.
NSFetchedResultsController
does more processing than just watch for saved objects. It handles deltas, makes calls to its delegates, etc. I am not saying it is bad in any way shape or form. What I am saying is that if you only care about when objects have changed in your relationship, you can do it pretty easily by just watching for the notifications.
In addition, there is no reason to retain anything since you are already holding onto the "Department" entity and therefore access its relationships. Holding onto the child objects "just in case" is a waste of memory. Let Core Data manage the memory, that is part of the reason for using it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With