I'm having an issue getting accurate updates from an NSFetchedResultsControllerDelegate after using an NSBatchDeleteRequest, the changes come through as an update type and not the delete type on the didChange delegate method. Is there a way to get the changes to come in as a delete? (I have different scenarios for delete vs update).
The delete request:
(uses a private context supplied by the caller)
fileprivate class func deletePeopleWith(ids: Set<Int>, usingContext context: NSManagedObjectContext) {
let fr: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Person")
var predicates: [NSPredicate] = []
ids.forEach {
predicates.append(NSPredicate(format: "id = %ld", $0))
}
fr.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
let dr = NSBatchDeleteRequest(fetchRequest: fr)
dr.affectedStores = context.parent?.persistentStoreCoordinator?.persistentStores
do {
try context.parent?.execute(dr)
context.parent?.refreshAllObjects()
print("Deleting person")
} catch let error as NSError {
let desc = "Could not delete person with batch delete request, with error: \(error.localizedDescription)"
debugPrint(desc)
}
}
Results in:
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
DispatchQueue.main.async {
let changeDesc = "Have change with indexPath of: \(indexPath), new index path of: \(newIndexPath) for object: \(anObject)"
var changeType = ""
switch type {
case .delete:
changeType = "delete"
case .insert:
changeType = "insert"
case .move:
changeType = "move"
case .update:
changeType = "update"
}
print(changeDesc)
print(changeType)
}
}
Printing:
Have change with indexPath of: Optional([0, 0]), new index path of: Optional([0, 0]) for object: *my core data object*
update
From Apple's documentation:
Batch deletes run faster than deleting the Core Data entities yourself in code because they operate in the persistent store itself, at the SQL level. As part of this difference, the changes enacted on the persistent store are not reflected in the objects that are currently in memory.
After a batch delete has been executed, remove any objects in memory that have been deleted from the persistent store.
See the Updating Your Application After Execution section for handling the objects deleted by NSBatchDeleteRequest.
Here is the sample, works for me. But i didn't find how to update deletion with animation, cause NSFetchedResultsControllerDelegate didn't fire.
#IBAction func didPressDelete(_ sender: UIBarButtonItem) {
let managedObjectContext = persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: Record.self))
let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
do {
// delete on persistance store level
try managedObjectContext.execute(deleteRequest)
// reload the whole context
managedObjectContext.reset()
try self.fetchedResultsController.performFetch()
tableV.reloadData()
} catch {
print("🍓")
}
}
Thanks.
Since NSBatchDeleteRequest deletes the managed objects at the persistentStore level (on disk), the most effective way to update the current context (in-memory) is by calling refreshAllObjects() on the context like so:
func batchDelete() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
let context = appDelegate.persistentContainer.viewContext
if let request = self.fetchedResultsController.fetchRequest as? NSFetchRequest<NSFetchRequestResult> {
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: request)
do {
try context.execute(batchDeleteRequest) // performs the deletion
appDelegate.saveContext()
context.refreshAllObjects() // updates the fetchedResultsController
} catch {
print("Batch deletion failed.")
}
}
}
}
No need for refetching all the objects or tableView.reloadData()!
Related
I know that when updating multiple rows of data, NSBatchUpdateRequest is a recommended way, as it is faster and consumed less memory.
However, what if we are only updating 1 row? Should we choose to update using NSBatchUpdateRequest or NSManagedObject? Is there any rule-of-thumb to decide the choice?
Using NSManagedObject
func updateName(_ objectID: NSManagedObjectID, _ name: String) {
let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext
backgroundContext.perform {
do {
let nsTabInfo = try backgroundContext.existingObject(with: objectID) as! NSTabInfo
nsTabInfo.name = name
RepositoryUtils.saveContextIfPossible(backgroundContext)
} catch {
backgroundContext.rollback()
error_log(error)
}
}
}
Using NSBatchUpdateRequest
func updateName(_ objectID: NSManagedObjectID, _ name: String) {
let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext
backgroundContext.perform {
do {
let batchUpdateRequest = NSBatchUpdateRequest(entityName: "NSTabInfo")
batchUpdateRequest.predicate = NSPredicate(format: "self == %#", objectID)
batchUpdateRequest.propertiesToUpdate = ["name": name]
batchUpdateRequest.resultType = .updatedObjectIDsResultType
let batchUpdateResult = try backgroundContext.execute(batchUpdateRequest) as? NSBatchUpdateResult
guard let batchUpdateResult = batchUpdateResult else { return }
guard let managedObjectIDs = batchUpdateResult.result else { return }
let changes = [NSUpdatedObjectsKey : managedObjectIDs]
coreDataStack.mergeChanges(changes)
} catch {
backgroundContext.rollback()
error_log(error)
}
}
}
May I know how can we decide to choose NSBatchUpdateRequest or NSManagedObject, when updating 1 row?
For one/few objects (that can be easily pulled into memory without issues), it is usually easier/recommended to -
fetch NSManagedObject into NSManagedObjectContext.
Perform your updates.
Save the context.
This saves you from having to merge the same set of changes to all other contexts in the app (which may have reference to the object being updated).
This works because NSManagedObjectContext fires notifications on save() calls that can be automatically observed by other contexts (if needed).
I have save values to entity method which save new data and updates existing data.
func saveSteps(_ serverJson: [[String: Any]]){
let stepService = StepService(context: context);
if(serverJson.count > 0){
for step in serverJson {
let stepTitle = step["stepTitle"] as? String ?? ""
let stepDescription = step["stepDescription"] as? String ?? ""
let stepId = step["_id"] as? String ?? ""
let predicate: NSPredicate = NSPredicate(format: "stepId=%#", stepId)
let stepList = stepService.get(withPredicate: predicate);
if(stepList.count == 0){
stepService.create(stepId: stepId, stepTitle: stepTitle, stepDescription: stepDescription);
}else{
if let updatableStep = stepList.first{
updatableStep.stepDescription = stepDescription //EXC_BAD_ACCESS Error Here
updatableStep.stepName = stepName
updatableStep.stepTitle = stepTitle
stepService.update(updatedStep: updatableStep)
}else{
stepService.create(stepId: stepId, stepTitle: stepTitle, stepDescription: stepDescription);
}
}
saveContext()
}
My Create update and get methods are in stepService
func create(stepId:String, stepDescription: String, stepTitle:String){
let newItem = NSEntityDescription.insertNewObject(forEntityName: "Steps", into: context) as! Steps //EXC_BAD_ACCESS Error Here
newItem.stepId = stepId
newItem.stepTitle = stepTitle
newItem.stepDescription = stepDescription
}
func update(updatedStep: Steps){
if let step = getById(id: updatedStep.objectID){
step.stepId = updatedStep.stepId
step.stepTitle = updatedStep.stepTitle
step.stepDescription = updatedStep.stepDescription
}
func get(withPredicate queryPredicate: NSPredicate) -> [Steps]{
let fetchRequest: NSFetchRequest<Steps> = Steps.fetchRequest()
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = queryPredicate
do {
let response = try context.fetch(fetchRequest)
return response
} catch let error as NSError {
// failure
print(error)
return [Steps]()
}
}
}
Mysave context method is
// Creating private queue to save the data to disk
lazy var savingModelcontext:NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.coordinator
return managedObjectContext
}()
// Creating Context to save in block main queue this will be temporary save
lazy var context:NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.parent = self.savingModelcontext
return managedObjectContext
}()
func saveContext () {
guard savingModelcontext.hasChanges || context.hasChanges else {
return
}
context.performAndWait {
do {
try self.context.save()
} catch let error as NSError {
print("Could not save in Context: \(error.localizedDescription)")
}
}
savingModelcontext.perform {
do {
try self.savingModelcontext.save()
} catch let error as NSError {
print("Could not save savingModelContext: \(error.localizedDescription)")
}
}
}
There are two places that core data crashes with same error message one is when i access the data to update the method and other is when i am trying to create a new item using NSEntityDescription.insertNewObject with entity name.
while saing i have tried Dispach queue with qos of userInitiated and default. I didn't use background as user might open some thing that might use this.
The problem is the crash is not consistanct and has never crashed when doing a debug which leads me to belive it is concurrency issue but the data is never deleted or read when being updated.
PS: I have read the questions with same and similar issues but i could not get a working answer here the question.
Kidly point out if i have made any mistakes
Thanks any help is appreciated
The Reason fo the crash was i was trying to change was that i was using and using private queue context in main thread and vise versa. to fix this using Group Dispach queue with desired QOS for private queue context and main thread for using main queue objects.
I've been struggling with this for days. I'll appreciate any help.
I have a Location NSManagedObject and an Image NSManagedObject, they have one-to-many relationship, i.e., one location has many images.
I have 2 screens, in the first one the user adds locations on the view context and they get added and retrieved without problems.
Now, in the second screen, I want to retrieve images based on the location selected in the first screen, then display the images in a Collection View. The images are first retrieved from flickr, then saved in the DB.
I want to save and retrieve images on a background context and this causes me a lot of problems.
When I try to save every image retrieved from flickr I get a warning stating that there is a dangling object and the relationship can' be established:
This is my saving code:
func saveImagesToDb () {
//Store the image in the DB along with its location on the background thread
if (doesImageExist()){
dataController.backgroundContext.perform {
for downloadedImage in self.downloadedImages {
print ("saving to context")
let imageOnMainContext = Image (context: self.dataController.viewContext)
let imageManagedObjectId = imageOnMainContext.objectID
let imageOnBackgroundContext = self.dataController.backgroundContext.object(with: imageManagedObjectId) as! Image
let locationObjectId = self.imagesLocation.objectID
let locationOnBackgroundContext = self.dataController.backgroundContext.object(with: locationObjectId) as! Location
let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = locationOnBackgroundContext
try? self.dataController.backgroundContext.save ()
}
}
}
}
As you can see in the code above I'm building NSManagedObject on the background context based on the ID retrieved from those on the view context. Every time saveImagesToDb is called I get the warning, so what's the problem?
In spite of the warning above, when I retrieve the data through a FetchedResultsController (which works on the background context). The Collection View sometimes view the images just fine and sometimes I get this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (4) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'
Here are some code snippets that are related to setting up the FetchedResultsController and updating the Collection View based on changes in the context or in the FetchedResultsController.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let imagesCount = fetchedResultsController.fetchedObjects?.count else {return 0}
return imagesCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print ("cell data")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! ImageCell
//cell.placeImage.image = UIImage (named: "placeholder")
let imageObject = fetchedResultsController.object(at: indexPath)
let imageData = imageObject.image
let uiImage = UIImage (data: imageData!)
cell.placeImage.image = uiImage
return cell
}
func setUpFetchedResultsController () {
print ("setting up controller")
//Build a request for the Image ManagedObject
let fetchRequest : NSFetchRequest <Image> = Image.fetchRequest()
//Fetch the images only related to the images location
let locationObjectId = self.imagesLocation.objectID
let locationOnBackgroundContext = self.dataController.backgroundContext.object(with: locationObjectId) as! Location
let predicate = NSPredicate (format: "location == %#", locationOnBackgroundContext)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "location", ascending: true)]
fetchedResultsController = NSFetchedResultsController (fetchRequest: fetchRequest, managedObjectContext: dataController.backgroundContext, sectionNameKeyPath: nil, cacheName: "\(latLongString) images")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch ()
} catch {
fatalError("couldn't retrive images for the selected location")
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
print ("object info changed in fecthed controller")
switch type {
case .insert:
print ("insert")
DispatchQueue.main.async {
print ("calling section items")
self.collectionView!.numberOfItems(inSection: 0)
self.collectionView.insertItems(at: [newIndexPath!])
}
break
case .delete:
print ("delete")
DispatchQueue.main.async {
self.collectionView!.numberOfItems(inSection: 0)
self.collectionView.deleteItems(at: [indexPath!])
}
break
case .update:
print ("update")
DispatchQueue.main.async {
self.collectionView!.numberOfItems(inSection: 0)
self.collectionView.reloadItems(at: [indexPath!])
}
break
case .move:
print ("move")
DispatchQueue.main.async {
self.collectionView!.numberOfItems(inSection: 0)
self.collectionView.moveItem(at: indexPath!, to: newIndexPath!)
}
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
print ("section info changed in fecthed controller")
let indexSet = IndexSet(integer: sectionIndex)
switch type {
case .insert:
self.collectionView!.numberOfItems(inSection: 0)
collectionView.insertSections(indexSet)
break
case .delete:
self.collectionView!.numberOfItems(inSection: 0)
collectionView.deleteSections(indexSet)
case .update, .move:
fatalError("Invalid change type in controller(_:didChange:atSectionIndex:for:). Only .insert or .delete should be possible.")
}
}
func addSaveNotificationObserver() {
removeSaveNotificationObserver()
print ("context onbserver notified")
saveObserverToken = NotificationCenter.default.addObserver(forName: .NSManagedObjectContextObjectsDidChange, object: dataController?.backgroundContext, queue: nil, using: handleSaveNotification(notification:))
}
func removeSaveNotificationObserver() {
if let token = saveObserverToken {
NotificationCenter.default.removeObserver(token)
}
}
func handleSaveNotification(notification:Notification) {
DispatchQueue.main.async {
self.collectionView!.numberOfItems(inSection: 0)
self.collectionView.reloadData()
}
}
What am I doing wrong? I'll appreciate any help.
I cannot tell you what the problem is with 1), but I think 2) is not (just) a problem with the database.
The error your are getting usually happens when you add or remove items/sections to a collectionview, but when numberOfItemsInSection is called afterwards the numbers don't add up. Example: you have 5 items and add 2, but then numberOfItemsInSection is called and returns 6, which creates the inconsistency.
In your case my guess would be that you add items with collectionView.insertItems(), but this line returns 0 afterwards:
guard let imagesCount = fetchedResultsController.fetchedObjects?.count else {return 0}
What also confused me in your code are these parts:
DispatchQueue.main.async {
print ("calling section items")
self.collectionView!.numberOfItems(inSection: 0)
self.collectionView.insertItems(at: [newIndexPath!])
}
You are requesting the number of items there, but you don't actually do anything with the result of the function. Is there a reason for that?
Even though I don't know what the CoreData issue is I would advise you to not access the DB in the tableview delegate methods, but to have an array of items that is fetched once and is updated only when the db content changes. That is probably more performant and a lot easier to maintain.
You have a common problem with UICollectionView inconsistency during batching update.
If you perform deletion/adding new items in the incorrect order UICollectionView might crash.
This problem has 2 typical solutions:
use -reloadData() instead of batch updates.
use third party libraries with safe implementation of batch update. Smth like this https://github.com/badoo/ios-collection-batch-updates
The problem is NSFetchedResultsController should only use a main thread NSManagedObjectContext.
Solution: create two NSManagedObjectContext objects, one in the main thread for NSFetchedResultsController and one in the background thread for performing the data writing.
let writeContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
let readContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
let fetchedController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: readContext, sectionNameKeyPath: nil, cacheName: nil)
writeContext.parent = readContext
UICollectionView will be updated properly once the data is saved in the writeContext with the following chain:
writeContext(background thread ) -> readContext(main thread) -> NSFetchedResultsController (main thread) -> UICollectionView (main thread)
I would like to thank Robin Bork, Eugene El, and meim for their answers.
I could finally solve both issues.
For the CollectionView problem, I felt like I was updating it too many times, as you can see in the code, I used to update it in two FetchedResultsController delegate methods, and also through an observer that observes any changes on the context. So I removed all of that and just used this method:
func controllerWillChangeContent(_ controller:
NSFetchedResultsController<NSFetchRequestResult>) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
In addition to that, CollectionView has a bug in maintaining the items count in a section sometimes as Eugene El mentioned. So, I just used reloadData to update its items and that worked well, I removed the usage of any method that adjusts its items item by item like inserting an item at a specific IndexPath.
For the dangling object problem. As you can see from the code, I had a Location object and an Image object. My location object was already filled with a location and it was coming from view context, so I just needed to create a corresponding object from it using its ID (as you see in the code in the question).
The problem was in the image object, I was creating an object on the view context (which contains no data inserted), get its ID, then build a corresponding object on the background context. After reading about this error and thinking about my code, I thought that the reason maybe because the Image object on the view context didn't contain any data. So, I removed the code that creates that object on the view context and created a one directly on the background context and used it as in the code below, and it worked!
func saveImagesToDb () {
//Store the image in the DB along with its location on the background thread
dataController.backgroundContext.perform {
for downloadedImage in self.downloadedImages {
let imageOnBackgroundContext = Image (context: self.dataController.backgroundContext)
//imagesLocation is on the view context
let locationObjectId = self.imagesLocation.objectID
let locationOnBackgroundContext = self.dataController.backgroundContext.object(with: locationObjectId) as! Location
let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = locationOnBackgroundContext
guard (try? self.dataController.backgroundContext.save ()) != nil else {
self.showAlert("Saving Error", "Couldn't store images in Database")
return
}
}
}
}
If anyone has another thought different from what I said about why the first method that first creates an empty Image object on the view context, then creates a corresponding one on the background context didn't work, please let us know.
I'm working with old xcdatamodel, it was created in xcode 7.3 (that's a crucial since I don't have the following issue on modern models). At the same time, this issue is not cured by simple changing Tool Version to Xcode 9.0 for my xcdatamodel.
I'm fetching data in for loop, in the thread of context I use for fetching data. When I try to fetch the entity that has already been fetched once, coreData crashes with EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP). Zombie tracking says [CFString copy]: message sent to deallocated instance 0x608000676b40.
This is the concept of what I do:
LegacyDatabaser.context.perform {
do {
for _ in 0..<10 {
let entity = try self.legacyDatabase.getEntity(forId:1)
print(entity.some_string_property) // <- crash here
}
} catch {
// ...
}
}
Here is the context initializer:
class LegacyDatabaser {
static var context: NSManagedObjectContext = LegacyDatabaseUtility.context
// ...
}
And
class LegacyDatabaseUtility {
fileprivate class var context: NSManagedObjectContext {
//let context = NSManagedObjectContext(concurrencyType:.privateQueueConcurrencyType)
//context.persistentStoreCoordinator = storeContainer.persistentStoreCoordinator
//return context // This didn't help also
return storeContainer.newBackgroundContext()
}
private static var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name:"MyDBName")
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
}
Here is the data fetcher:
func getEntity(forId id: NSNumber) throws -> MyEntity? {
// Create predicate
let predicate = NSPredicate(format:"id_local == %#", id)
// Find items in db
let results = try LegacyDatabaseUtility.find(predicate:predicate, sortDescriptors:nil, in:LegacyDatabaser.context)
// Check it
if results.count == 1 {
if let result = results.first as? MyEntity {
return result
} else {
return nil
}
} else {
return nil
}
}
And:
static func find(predicate:NSPredicate?, sortDescriptors:[NSSortDescriptor]?, in context: NSManagedObjectContext) throws -> [NSManagedObject] {
// Create a request
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName:"MyEntity")
// Apply predicate
if let predicate = predicate {
fetchRequest.predicate = predicate
}
// Apply sorting
if let sortDescriptors = sortDescriptors {
fetchRequest.sortDescriptors = sortDescriptors
}
// Run the fetchRequest
return try context.fetch(fetchRequest)
}
I don't address the context somewhere in a parallel, I'm sure I use the correct thread and context (I tested the main context also, the same result). What I'm doing wrong, why re-fetching the same entity fails?
If anyone catches any quirk crashes like one I described above, check the name of properties in your NSManagedObject. In my case, crashes were on call new_id property which is, I guess, kinda reserved name. Once I renamed this property, the crashes stopped.
I've been reading all the documentation about UISearchDisplayController and its delegate but I can't find any way to animate the table view when the search criteria change.
I'm using these two methods :
They both return YES but still can't find any way to do something similar to :
I don't know if it's important but I'm using an NSfetchedResultsController to populate the UITableView in the UISearchDisplayController
That's it thanks !
When the search string or scope has changed, you assign a new fetch request for the fetched results controller and therefore have to call performFetch to get a new result set. performFetch resets the state of the controller, and it does not trigger any of the FRC delegate methods.
So the table view has to be updated "manually" after changing the fetch request. In most sample programs, this is done by
calling reloadData on the search table view, or
returning YES from shouldReloadTableForSearchString or shouldReloadTableForSearchScope.
The effect is the same: The search table view is reloaded without animation.
I don't think there is any built-in/easy method to animate the table view update when the search predicate changes. However, you could try the following (this is just an idea, I did not actually try this myself):
Before changing the fetch request, make a copy of the old result set:
NSArray *oldList = [[fetchedResultsController fetchedObjects] copy];
Assign the new fetch request to the FRC and call performFetch.
Get the new result set:
NSArray *newList = [fetchedResultsController fetchedObjects];
Do not call reloadData on the search table view.
Compare oldList and newList to detect new and removed objects. Call insertRowsAtIndexPaths for the new objects and deleteRowsAtIndexPaths for the removed objects. This can be done by traversing both lists in parallel.
Return NO from shouldReloadTableForSearchString or shouldReloadTableForSearchScope.
As I said, this is just an idea but I think it could work.
I know this question is old, but I recently faced this and wanted a solution that would work regardless of how the NSFetchedResultsController was initialized. It's based on #martin-r's answer above.
Here's the corresponding gist: https://gist.github.com/stephanecopin/4ad7ed723f9857d96a777d0e7b45d676
import CoreData
extension NSFetchedResultsController {
var predicate: NSPredicate? {
get {
return self.fetchRequest.predicate
}
set {
try! self.setPredicate(newValue)
}
}
var sortDescriptors: [NSSortDescriptor]? {
get {
return self.fetchRequest.sortDescriptors
}
set {
try! self.setSortDescriptors(newValue)
}
}
func setPredicate(predicate: NSPredicate?) throws {
try self.setPredicate(predicate, sortDescriptors: self.sortDescriptors)
}
func setSortDescriptors(sortDescriptors: [NSSortDescriptor]?) throws {
try self.setPredicate(self.predicate, sortDescriptors: sortDescriptors)
}
func setPredicate(predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?) throws {
func updateProperties() throws {
if let cacheName = cacheName {
NSFetchedResultsController.deleteCacheWithName(cacheName)
}
self.fetchRequest.predicate = predicate
self.fetchRequest.sortDescriptors = sortDescriptors
try self.performFetch()
}
guard let delegate = self.delegate else {
try updateProperties()
return
}
let previousSections = self.sections ?? []
let previousSectionsCount = previousSections.count
var previousObjects = Set(self.fetchedObjects as? [NSManagedObject] ?? [])
var previousIndexPaths: [NSManagedObject: NSIndexPath] = [:]
previousObjects.forEach {
previousIndexPaths[$0] = self.indexPathForObject($0)
}
try updateProperties()
let newSections = self.sections ?? []
let newSectionsCount = newSections.count
var newObjects = Set(self.fetchedObjects as? [NSManagedObject] ?? [])
var newIndexPaths: [NSManagedObject: NSIndexPath] = [:]
newObjects.forEach {
newIndexPaths[$0] = self.indexPathForObject($0)
}
let updatedObjects = newObjects.intersect(previousObjects)
previousObjects.subtractInPlace(updatedObjects)
newObjects.subtractInPlace(updatedObjects)
var moves: [(object: NSManagedObject, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath)] = []
updatedObjects.forEach { updatedObject in
if let previousIndexPath = previousIndexPaths[updatedObject],
let newIndexPath = newIndexPaths[updatedObject]
{
if previousIndexPath != newIndexPath {
moves.append((updatedObject, previousIndexPath, newIndexPath))
}
}
}
if moves.isEmpty && previousObjects.isEmpty && newObjects.isEmpty {
// Nothing really changed
return
}
delegate.controllerWillChangeContent?(self)
moves.forEach {
delegate.controller?(self, didChangeObject: $0.object, atIndexPath: $0.fromIndexPath, forChangeType: .Move, newIndexPath: $0.toIndexPath)
}
let sectionDifference = newSectionsCount - previousSectionsCount
if sectionDifference < 0 {
(newSectionsCount..<previousSectionsCount).forEach {
delegate.controller?(self, didChangeSection: previousSections[$0], atIndex: $0, forChangeType: .Delete)
}
} else if sectionDifference > 0 {
(previousSectionsCount..<newSectionsCount).forEach {
delegate.controller?(self, didChangeSection: newSections[$0], atIndex: $0, forChangeType: .Insert)
}
}
previousObjects.forEach {
delegate.controller?(self, didChangeObject: $0, atIndexPath: previousIndexPaths[$0], forChangeType: .Delete, newIndexPath: nil)
}
newObjects.forEach {
delegate.controller?(self, didChangeObject: $0, atIndexPath: nil, forChangeType: .Insert, newIndexPath: newIndexPaths[$0])
}
delegate.controllerDidChangeContent?(self)
}
}
It exposes 2 properties on the NSFetchedResultsController, predicate and sortDescriptors which mirrors those found in the fetchRequest.
When either of these properties are set, the controller will automatically compute changes the changes and send them through the delegate, so hopefully there is no major code changes.
If you don't want animations, you can still directly set predicate or sortDescriptors on the fetchRequest itself.