NSFetchedResultsController doesn't update count after deleteDoes NSFetchedResultsController Observe All Changes to Persistent Store?How to detect tableView cell touched or clicked in swiftExpand and Collapse tableview cellsUpdate or reload UITableView after completion of delete action on detail viewTableView not displaying text with JSON data from API callAdding a custom UIViewcontroller to subview programmatically but getting an error message “Cannot convert value of type…”Unable to generate a new section map with old section count: 1 and new section count: 0 with FetchedResultsControllerI am trying to append a message for my tableview but it is not appending.please help meSwift Error - Use of undeclared type 'cell' - Collection ViewGit is not working after macOS Mojave Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

How would a aircraft visually signal "in distress"?

How does an ordinary object become radioactive?

How is water heavier than petrol, even though its molecular weight is less than petrol?

What can plausibly explain many of my very long and low-tech bridges?

Using a found spellbook as a Sorcerer-Wizard multiclass

Can an Aarakocra use a shield while flying?

Russian equivalents of "no love lost"

What language is the software written in on the ISS?

Why did Canadian English remain so close to standard U.S English?

Do any instruments not produce overtones?

How do governments keep track of their issued currency?

What is the actual quality of machine translations?

Where does "0 packages can be updated." come from?

What could have caused a rear derailleur to end up in the back wheel suddenly?

When conversion from Integer to Single may lose precision

Why would future John risk sending back a T-800 to save his younger self?

How to generate all commutative pairings of list elements?

Preventing Employees from either switching to Competitors or Opening Their Own Business

Inconsistent behavior of compiler optimization of unused string

Should I compare a std::string to "string" or "string"s?

What can I, as a user, do about offensive reviews in App Store?

Is it possible to 'live off the sea'

Is open-sourcing the code of a webapp not recommended?

Smooth switching between 12 V batteries, with a toggle switch



NSFetchedResultsController doesn't update count after delete


Does NSFetchedResultsController Observe All Changes to Persistent Store?How to detect tableView cell touched or clicked in swiftExpand and Collapse tableview cellsUpdate or reload UITableView after completion of delete action on detail viewTableView not displaying text with JSON data from API callAdding a custom UIViewcontroller to subview programmatically but getting an error message “Cannot convert value of type…”Unable to generate a new section map with old section count: 1 and new section count: 0 with FetchedResultsControllerI am trying to append a message for my tableview but it is not appending.please help meSwift Error - Use of undeclared type 'cell' - Collection ViewGit is not working after macOS Mojave Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm learning CoreData on mac os. I have a demo program which basically works, except that when I delete a row from my tableView,



fetchedResultsController.fetchedObjects?.count


hasn't updated.



Revelevant properties are defined as follows



 var container: NSPersistentContainer!
var fetchedResultsController: NSFetchedResultsController<Commit>!
var count: Int get
if fetchedResultsController == nil return 0
return fetchedResultsController.fetchedObjects?.count ?? 0



The remove method:



 func remove(itemAt index: Int) 
guard let n = fetchedResultsController.fetchedObjects?.count,
index < n && index >= 0,
let commit = fetchedResultsController.fetchedObjects?[index] else return
container.viewContext.delete(commit)
saveContext()
ddt("remove (count)", caller: self)




The count after remove hasn't been updated, however the persistent store is correct. If I remove another row, it still doesn't update, but if I change predicate (even to the nil predicate) it refreshes properly.



On relaunch, all is updated.



My delegate doesn't do anything. The table gets updated in its delegate:



 func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] 
// left swipe
if edge == .trailing
let deleteAction = NSTableViewRowAction(style: .destructive, title: "Delete", handler:
[unowned self] (rowAction, row) in
self.dataContainer.remove(itemAt: row)
tableView.removeRows(at: [row], withAnimation: .slideLeft)
)
deleteAction.backgroundColor = NSColor.red
return [deleteAction]

// Anything other than left does nothing
return []



What have I left out?



(ddt, for those too young to remember, was an insecticide banned many years ago because it tended to propagate up the food chain, killing off birds, among other species. I think it's safe to use on bugs in Swift.)










share|improve this question




























    0















    I'm learning CoreData on mac os. I have a demo program which basically works, except that when I delete a row from my tableView,



    fetchedResultsController.fetchedObjects?.count


    hasn't updated.



    Revelevant properties are defined as follows



     var container: NSPersistentContainer!
    var fetchedResultsController: NSFetchedResultsController<Commit>!
    var count: Int get
    if fetchedResultsController == nil return 0
    return fetchedResultsController.fetchedObjects?.count ?? 0



    The remove method:



     func remove(itemAt index: Int) 
    guard let n = fetchedResultsController.fetchedObjects?.count,
    index < n && index >= 0,
    let commit = fetchedResultsController.fetchedObjects?[index] else return
    container.viewContext.delete(commit)
    saveContext()
    ddt("remove (count)", caller: self)




    The count after remove hasn't been updated, however the persistent store is correct. If I remove another row, it still doesn't update, but if I change predicate (even to the nil predicate) it refreshes properly.



    On relaunch, all is updated.



    My delegate doesn't do anything. The table gets updated in its delegate:



     func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] 
    // left swipe
    if edge == .trailing
    let deleteAction = NSTableViewRowAction(style: .destructive, title: "Delete", handler:
    [unowned self] (rowAction, row) in
    self.dataContainer.remove(itemAt: row)
    tableView.removeRows(at: [row], withAnimation: .slideLeft)
    )
    deleteAction.backgroundColor = NSColor.red
    return [deleteAction]

    // Anything other than left does nothing
    return []



    What have I left out?



    (ddt, for those too young to remember, was an insecticide banned many years ago because it tended to propagate up the food chain, killing off birds, among other species. I think it's safe to use on bugs in Swift.)










    share|improve this question
























      0












      0








      0








      I'm learning CoreData on mac os. I have a demo program which basically works, except that when I delete a row from my tableView,



      fetchedResultsController.fetchedObjects?.count


      hasn't updated.



      Revelevant properties are defined as follows



       var container: NSPersistentContainer!
      var fetchedResultsController: NSFetchedResultsController<Commit>!
      var count: Int get
      if fetchedResultsController == nil return 0
      return fetchedResultsController.fetchedObjects?.count ?? 0



      The remove method:



       func remove(itemAt index: Int) 
      guard let n = fetchedResultsController.fetchedObjects?.count,
      index < n && index >= 0,
      let commit = fetchedResultsController.fetchedObjects?[index] else return
      container.viewContext.delete(commit)
      saveContext()
      ddt("remove (count)", caller: self)




      The count after remove hasn't been updated, however the persistent store is correct. If I remove another row, it still doesn't update, but if I change predicate (even to the nil predicate) it refreshes properly.



      On relaunch, all is updated.



      My delegate doesn't do anything. The table gets updated in its delegate:



       func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] 
      // left swipe
      if edge == .trailing
      let deleteAction = NSTableViewRowAction(style: .destructive, title: "Delete", handler:
      [unowned self] (rowAction, row) in
      self.dataContainer.remove(itemAt: row)
      tableView.removeRows(at: [row], withAnimation: .slideLeft)
      )
      deleteAction.backgroundColor = NSColor.red
      return [deleteAction]

      // Anything other than left does nothing
      return []



      What have I left out?



      (ddt, for those too young to remember, was an insecticide banned many years ago because it tended to propagate up the food chain, killing off birds, among other species. I think it's safe to use on bugs in Swift.)










      share|improve this question














      I'm learning CoreData on mac os. I have a demo program which basically works, except that when I delete a row from my tableView,



      fetchedResultsController.fetchedObjects?.count


      hasn't updated.



      Revelevant properties are defined as follows



       var container: NSPersistentContainer!
      var fetchedResultsController: NSFetchedResultsController<Commit>!
      var count: Int get
      if fetchedResultsController == nil return 0
      return fetchedResultsController.fetchedObjects?.count ?? 0



      The remove method:



       func remove(itemAt index: Int) 
      guard let n = fetchedResultsController.fetchedObjects?.count,
      index < n && index >= 0,
      let commit = fetchedResultsController.fetchedObjects?[index] else return
      container.viewContext.delete(commit)
      saveContext()
      ddt("remove (count)", caller: self)




      The count after remove hasn't been updated, however the persistent store is correct. If I remove another row, it still doesn't update, but if I change predicate (even to the nil predicate) it refreshes properly.



      On relaunch, all is updated.



      My delegate doesn't do anything. The table gets updated in its delegate:



       func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] 
      // left swipe
      if edge == .trailing
      let deleteAction = NSTableViewRowAction(style: .destructive, title: "Delete", handler:
      [unowned self] (rowAction, row) in
      self.dataContainer.remove(itemAt: row)
      tableView.removeRows(at: [row], withAnimation: .slideLeft)
      )
      deleteAction.backgroundColor = NSColor.red
      return [deleteAction]

      // Anything other than left does nothing
      return []



      What have I left out?



      (ddt, for those too young to remember, was an insecticide banned many years ago because it tended to propagate up the food chain, killing off birds, among other species. I think it's safe to use on bugs in Swift.)







      swift macos core-data






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 16:21









      RonRon

      360118




      360118






















          1 Answer
          1






          active

          oldest

          votes


















          2















          • First of all declare the fetchedResultsController as lazy non-optional property and set the delegate in the closure



            lazy var fetchedResultsController: NSFetchedResultsController<Commit> = 

            ...

            let controller = NSFetchedResultsController( ...
            controller.delegate = self

            ...
            return controller
            ()



          • Adopt NSFetchedResultsControllerDelegate and implement the delegate methods



            • func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)

            • func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)

            • func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)



          • To delete a record in a NSTableViewRowAction get the item at indexPath and delete the record in the Core Data stack. You don't need to check the index, the row does exist



            let indexPath = IndexPath(item: row, section: 0)
            let commit = fetchedResultsController.object(at: indexPath)
            container.viewContext.delete(commit)
            saveContext()


            The NSFetchedResultsControllerDelegate methods manage the update of the UI







          share|improve this answer

























          • Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

            – Ron
            Mar 24 at 18:24











          • My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

            – Ron
            Mar 25 at 3:11











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325900%2fnsfetchedresultscontroller-doesnt-update-count-after-delete%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2















          • First of all declare the fetchedResultsController as lazy non-optional property and set the delegate in the closure



            lazy var fetchedResultsController: NSFetchedResultsController<Commit> = 

            ...

            let controller = NSFetchedResultsController( ...
            controller.delegate = self

            ...
            return controller
            ()



          • Adopt NSFetchedResultsControllerDelegate and implement the delegate methods



            • func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)

            • func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)

            • func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)



          • To delete a record in a NSTableViewRowAction get the item at indexPath and delete the record in the Core Data stack. You don't need to check the index, the row does exist



            let indexPath = IndexPath(item: row, section: 0)
            let commit = fetchedResultsController.object(at: indexPath)
            container.viewContext.delete(commit)
            saveContext()


            The NSFetchedResultsControllerDelegate methods manage the update of the UI







          share|improve this answer

























          • Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

            – Ron
            Mar 24 at 18:24











          • My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

            – Ron
            Mar 25 at 3:11















          2















          • First of all declare the fetchedResultsController as lazy non-optional property and set the delegate in the closure



            lazy var fetchedResultsController: NSFetchedResultsController<Commit> = 

            ...

            let controller = NSFetchedResultsController( ...
            controller.delegate = self

            ...
            return controller
            ()



          • Adopt NSFetchedResultsControllerDelegate and implement the delegate methods



            • func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)

            • func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)

            • func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)



          • To delete a record in a NSTableViewRowAction get the item at indexPath and delete the record in the Core Data stack. You don't need to check the index, the row does exist



            let indexPath = IndexPath(item: row, section: 0)
            let commit = fetchedResultsController.object(at: indexPath)
            container.viewContext.delete(commit)
            saveContext()


            The NSFetchedResultsControllerDelegate methods manage the update of the UI







          share|improve this answer

























          • Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

            – Ron
            Mar 24 at 18:24











          • My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

            – Ron
            Mar 25 at 3:11













          2












          2








          2








          • First of all declare the fetchedResultsController as lazy non-optional property and set the delegate in the closure



            lazy var fetchedResultsController: NSFetchedResultsController<Commit> = 

            ...

            let controller = NSFetchedResultsController( ...
            controller.delegate = self

            ...
            return controller
            ()



          • Adopt NSFetchedResultsControllerDelegate and implement the delegate methods



            • func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)

            • func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)

            • func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)



          • To delete a record in a NSTableViewRowAction get the item at indexPath and delete the record in the Core Data stack. You don't need to check the index, the row does exist



            let indexPath = IndexPath(item: row, section: 0)
            let commit = fetchedResultsController.object(at: indexPath)
            container.viewContext.delete(commit)
            saveContext()


            The NSFetchedResultsControllerDelegate methods manage the update of the UI







          share|improve this answer
















          • First of all declare the fetchedResultsController as lazy non-optional property and set the delegate in the closure



            lazy var fetchedResultsController: NSFetchedResultsController<Commit> = 

            ...

            let controller = NSFetchedResultsController( ...
            controller.delegate = self

            ...
            return controller
            ()



          • Adopt NSFetchedResultsControllerDelegate and implement the delegate methods



            • func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)

            • func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)

            • func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)



          • To delete a record in a NSTableViewRowAction get the item at indexPath and delete the record in the Core Data stack. You don't need to check the index, the row does exist



            let indexPath = IndexPath(item: row, section: 0)
            let commit = fetchedResultsController.object(at: indexPath)
            container.viewContext.delete(commit)
            saveContext()


            The NSFetchedResultsControllerDelegate methods manage the update of the UI








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 at 16:50

























          answered Mar 24 at 16:44









          vadianvadian

          162k17176198




          162k17176198












          • Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

            – Ron
            Mar 24 at 18:24











          • My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

            – Ron
            Mar 25 at 3:11

















          • Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

            – Ron
            Mar 24 at 18:24











          • My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

            – Ron
            Mar 25 at 3:11
















          Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

          – Ron
          Mar 24 at 18:24





          Thank you. Much cleaner, and you helped me understand the row/IndexPath thing better. I think. But... the count and sections[0].numberOfObjects still does not get updated. I can force it by refetching, so this is not a roadblock, but I'm still puzzled by this behavior.

          – Ron
          Mar 24 at 18:24













          My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

          – Ron
          Mar 25 at 3:11





          My bad. Careless error, didn't hook things up right. All appears correct. Thanks again.

          – Ron
          Mar 25 at 3:11



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325900%2fnsfetchedresultscontroller-doesnt-update-count-after-delete%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript