Fatal error: UnsafeRawBufferPointer with negative count on deleting object(s) from Core Data/NSFetchedResultsController
Asked Answered
T

2

11

It is the first time for me working with AppKit and a NSTableView. It is backed by a NSFetchedResultsController for Core Data. When there are changes to the dataset, a Notification is being sent:

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    guard let links = self.fetchedResultsController.fetchedObjects else {
        return
    }

    if self.viewContext.hasChanges {
        try? self.viewContext.save()
    }
        
    self._links = links
    NotificationCenter.default.post(name: .reloadLinkList, object: nil)
}
NotificationCenter.default.publisher(for: .reloadLinkList).receive(on: RunLoop.main).sink { notification in
    self.list.tableView.reloadData()
    self.list.linksModel.selectedRows = IndexSet([])
}
.store(in: &cancellables)

This works great for inserting and updating data. When I try to delete something, I get:

Thread 1: Fatal error: UnsafeRawBufferPointer with negative count

The code for deleting selected objects looks as following:

// selector methode for UIMenuItem`s action
@objc func onDeleteSelectedLinks(_ sender: AnyObject) {
    list.linksModel.deleteLinks(links: selectedLinks)
}
// Method for deleting links from the view context
func deleteLinks(links: [LBLink]) {
    for link in links {
        self.viewContext.delete(link)
    }
}

Thank you for any help in advance!

Tbar answered 15/6, 2022 at 15:48 Comment(1)
S
15

Error when i worked in my project:

error when i worked in my project

How I solved the problem

step 1:

step 1

Copy name of your coredata(if you dont know that, it is with ".xcdatamodeld " format , in my case. CoreDataOneToMany.xcdatamodeld)

Step 2:

step 2

Go to DataController file(if you dont know what is DataController it is used to connect swift ui with coredata , you can refer more from hacking with swift if you want)

Step 3:

step 3

Check name both names are same (in my case its different so its showing error:"Fatal error: UnsafeRawBufferPointer with negative count")

Error fixed:

Error fixed

in my case and built successfully , this may help you

Swelling answered 1/12, 2022 at 9:37 Comment(1)
It solved my problem. To sum it up: the name set for the xcdatamodeld must be the same as the name set for the "name" parameter in NSPersistentContainerMil
D
1

in my case i simply forgot to import the CoreData framework in the top op the file.

import CoreData
Dixson answered 31/8, 2023 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.