I've been playing with Core Data for the past 18 hours or so. I'm fetching data with NSFetchedResultsController and shows data with UITableView. Adding a new record and deleting the selected record aren't my problems.
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Instance variables
private let persistentContainer = NSPersistentContainer(name: "Profiles") // core data model file (.xcdatamodeld)
var managedObjectContext: NSManagedObjectContext?
// MARK: - IBOutlets
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// loading persistentContainer //
persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
if let error = error {
print("Unable to Load Persistent Store")
} else {
do {
try self.fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.localizedDescription)")
}
}
}
// notifications //
NotificationCenter.default.addObserver(self, selector: #selector(profileDidUpdate), name: NSNotification.Name(rawValue: "HomeViewControllerPictureDidSelect"), object: nil)
}
// MARK: - fetchedResultsController(controller with the entity)
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Person> = {
// Create Fetch Request with Entity
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "lastName", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
// MARK: - fetchedResultsController
// MARK: - Notifications
#objc func profileDidUpdate(notification: NSNotification) {
let profile = notification.object as! Profile
let context = persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)
let newPerson = NSManagedObject(entity: entity!, insertInto: context)
newPerson.setValue(profile.uuid, forKey: "uuid") // uuid is used to make each record unique
newPerson.setValue(profile.firstName, forKey: "firstName")
newPerson.setValue(profile.lastName, forKey: "lastName")
newPerson.setValue(profile.age, forKey: "age")
newPerson.setValue(profile.pictData, forKey: "pictData")
do {
try context.save()
print("saved...")
} catch {
print("failed saving")
}
}
// MARK: - Notifications
}
extension HomeViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
tableView.insertRows(at: [indexPath], with: .fade)
}
break;
case .delete:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
break;
default:
print("...")
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
}
}
Shown above, I create a new record from another view controller, which sends an object of a model (Profile) to the current view controller (HomeViewController). I don't have to reload the table thanks to NSFetchedResultsController.
The entity has several attributes (age, firstName, lastName, pictData, uuid). And I want to change the selected record in the list with two attributes: firstName and lastName. The uuid attribute is used to identify a specific record.
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBAction func editTapped(_ sender: UIButton) {
guard let indexPath = tableView.indexPathForSelectedRow else {
return
}
let selectedRow = indexPath.row
if selectedRow >= 0 {
editRecord(index: selectedRow)
}
}
func editRecord(index: Int) {
let indexPath = IndexPath(row: index, section: 0)
let person = fetchedResultsController.object(at: indexPath)
let uuid = person.uuid!
let context = self.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
fetchRequest.predicate = NSPredicate(format: "uuid == %#", uuid)
do {
let result = try context.fetch(fetchRequest)
if (result.count > 0) {
let managedObject = result[0] as! NSManagedObject
managedObject.setValue("Donald", forKey: "firstName")
managedObject.setValue("Washington", forKey: "lastName")
try context.save()
print("Changes saved...")
}
} catch {
print("Failed")
}
}
}
Now, if I click on the edit button, the app won't update the list immediately. If I restart the app, I see changes. So how can I update the table with NSFetchedResultsController when I make changes to the selected record? Thanks.
Since you're using the NSFetchedResultsControllerDelegate, you need to handle (for your particular use case), the following cases for the NSFetchedResultsChangeType in your didChange method:
insert
delete
update
Your function should look something like this:
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
tableView.insertRows(at: [indexPath], with: .fade)
}
break;
case .delete:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
break;
case .update:
tableView.reloadRows(at: [indexPath], with: .automatic)
break;
default:
print("...")
}
}
Related
My application has two tab bars. The first one presents a list of games added on view controller and save them on the core data database. Switching on the second tab/view reads from the database and presents it inside a table view. I implemented the NSFetchedResultsControllerDelegate with a fetch method. When I add the first item to the context on the first tab and switch to second tab, FRC delegate methods (controllerWillChangeContent(_:), controller(_:didChange:at:for:newIndexPath:), controllerDidChangeContent(_:)) are not getting called and the table view is empty while I can see arrayOfGamesCount = 1. But when I add a second item, I can see all FRC delegate methods are getting call when I switch to second tab bar. And TableView display one rows while arrayOfGamesCount = 2
The first tab bar have 2 view controllers.(AddGameViewController and WelcomeViewController) AddGameVC is used to grab data from textfields and send it to welcomeVC.
import UIKit
import CoreData
class WelcomeViewController: UIViewController,SendGameDataDelegate, UIAdaptivePresentationControllerDelegate {
var games : [Game]? = []
var gamesMo: [GameMo]? = []
var gamed: GameMo?
var game : Game?
func ShouldSendGame(game: Game) {
self.game = game
print("\(game)")
games?.append(game)
}
#IBAction func endWLButton(_ sender: UIButton) {
saveDataToCoreData()
print("number of games from gamesMoCount is \(gamesMo?.count ?? 0)")
games?.removeAll()
reloadCollectionViewData()
}
func saveDataToCoreData (){
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
gamed = GameMo(context: appDelegate.persistentContainer.viewContext)
if games != nil {
for game in games! {
gamed?.goal = Int32(game.goal ?? 0 )
gamed?.rivalGoal = Int32(game.rivalGoal ?? 0)
gamed?.shot = Int32(game.shots ?? 0)
gamed?.rivalShot = Int32(game.rivalGoal ?? 0)
gamed?.rivalCorners = Int32(game.rivalsCorner ?? 0)
gamed?.corners = Int32(game.corners ?? 0)
gamesMo?.append(gamed!)
}
print("Saving data to context ....")
appDelegate.saveContext()
}
}
}
}
extension WelcomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return games?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let gameIndex = games?[indexPath.row] {
let userGameScore = gameIndex.goal
let rivalGameScore = gameIndex.rivalGoal
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FormCell", for: indexPath) as? FormCollectionViewCell {
cell.setCell(userScores: userGameScore!, rivalScores: rivalGameScore! )
return cell
}
}
return UICollectionViewCell ()
}
}
The second tab bar have only one VC: AllWLeagueController used to display items from the the database.
import UIKit
import CoreData
class AllWLeagueController : UITableViewController {
var fetchRequestController : NSFetchedResultsController<GameMo>!
var arrayOfGamesModel : [[GameMo]]? = []
var gameMo: GameMo?
var gamesMo: [GameMo] = []
override func viewDidLoad() {
validation(object: arrayOfGamesModel)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchRequest()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("arrayOfGamesModelcount est \(arrayOfGamesModel?.count ?? 0)")
return arrayOfGamesModel?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let weekL = arrayOfGamesModel?[indexPath.row] {
if let cell = tableView.dequeueReusableCell(withIdentifier: "WL") as? AllWLeaguesTableViewCell {
let winCounts = WLManager.winCountMethod(from: weekL)
let lossCounts = WLManager.lossCountMethod(from:weekL)
cell.setOulet(win: winCounts, loss: lossCounts, rankName: rankString)
cellLayer(with: cell)
return cell
}
}
}
extension AllWLeagueController: NSFetchedResultsControllerDelegate {
func fetchRequest () {
let fetchRequest = NSFetchRequest<GameMo>(entityName: "Game")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "win", ascending: true)]
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
let context = appDelegate.persistentContainer.viewContext
// fetch result controller
fetchRequestController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchRequestController.delegate = self
do{
try fetchRequestController.performFetch()
if let fetchedObjects = fetchRequestController.fetchedObjects {
gamesMo = fetchedObjects
print("Fetech Request Activated")
print(gamesMo)
}
}catch{
fatalError("Failed to fetch entities: \(error)")
}
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
print("TableView beginupdates")
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
if let newIndexPath = newIndexPath {
print("insert")
tableView.insertRows(at: [newIndexPath], with: .fade)
}
case .delete:
if let indexPath = indexPath {
print("delete")
tableView.deleteRows(at: [indexPath], with: .fade)
}
case .update:
if let indexPath = indexPath {
print("update")
tableView.reloadRows(at: [indexPath], with: .fade)
}
default:
tableView.reloadData()
}
if let fetchedObjects = controller.fetchedObjects {
gamesMo = fetchedObjects as! [GameMo]
print("we are about to append arrayOfGamesModel")
arrayOfGamesModel?.append(gamesMo)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
print("TableView endupdates")
tableView.endUpdates()
}
}
You are making a fatal mistake. In saveDataToCoreData only one instance is created and then it's being overwritten with the game data in each iteration of the array. So your array gamesMo may contain multiple items but it's always the same instance and only one instance is saved into the context.
Replace saveDataToCoreData with
func saveDataToCoreData (){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
guard let games = games else { return }
for game in games {
let newGame = GameMo(context: appDelegate.persistentContainer.viewContext)
newGame.goal = Int32(game.goal ?? 0 )
newGame.rivalGoal = Int32(game.rivalGoal ?? 0)
newGame.shot = Int32(game.shots ?? 0)
newGame.rivalShot = Int32(game.rivalGoal ?? 0)
newGame.rivalCorners = Int32(game.rivalsCorner ?? 0)
newGame.corners = Int32(game.corners ?? 0)
gamesMo.append(newGame)
}
print("Saving data to context ....")
appDelegate.saveContext()
}
Another bad practice is to create new fetch results controllers in viewWillAppear. It's highly recommended to create one controller as lazy instantiated property – as well as the managed object context – for example
lazy var context : NSManagedObjectContext = {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}()
lazy var fetchRequestController : NSFetchedResultsController<GameMo> = {
let fetchRequest = NSFetchRequest<GameMo>(entityName: "Game")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "win", ascending: true)]
// fetch result controller
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
do {
try frc.performFetch()
if let fetchedObjects = frc.fetchedObjects {
self.gamesMo = fetchedObjects
print("Fetech Request Activated")
print(gamesMo)
}
} catch{
fatalError("Failed to fetch entities: \(error)")
}
return frc
}()
Force unwrapping AppDelegate is perfectly fine. Your app won't even launch if AppDelegate was missing.
I recommend also to use less ambiguous variable names. games, gamesMo, gamed and game look very similar and can cause confusion.
I'm fetching some items (NSManagedObject) in viewDidLoad, and i'm using the NSFetchedResultsController delegates to update tableView cells in swift ios (the delegates from Apple docs for insertion, deletion etc.), the issue is that when I add an item to core data of the same ManagedObject type, i expect the table to update with the new item, but instead the last item is removed from the tableview and the new one isn't added. I only see the new item when I load the screen again... what could be wrong?
Here is my fetchedResultsController:
lazy var fetchedResultsController: NSFetchedResultsController<Message> = {
let context = CoreDataManager.shared.persistentContainer.viewContext
let request: NSFetchRequest<Message> = Message.fetchRequest()
request.sortDescriptors = [
NSSortDescriptor(key: "createdAt", ascending: true)
]
request.fetchLimit = 40
let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
// fetch only messages with that recipient id of the chat.
let recipientId = "\(chat!.recipientId)"
request.predicate = NSPredicate(format: "recipientId == %#", recipientId)
return frc
}()
and here is how i'm creating and adding a new message
func createNewTextMessage(recipientId: String, content: String) {
...
guard let id = Int32(recipientId) else { return }
guard let chat = fetchSingleChat(recipientId: id) else { return }
let context = persistentContainer.viewContext
let message = Message(context: context)
let date = Date()
message.chatId = chat.id
message.createdAt = date
message.isRead = false
message.senderId = Int32(currentUserId)
message.senderName = currentUserName
message.senderPhoneNumber = currentUserPhoneNumber
message.status = MessageStatus.unsent.rawValue
message.type = MessageType.text.rawValue
message.owner = MessageOwnerType.mine.rawValue
message.content = content
message.recipientId = chat.recipientId
message.recipientName = chat.title
message.messageId = "\(currentUserToken)_\(date.millisecondsSince1970)"
// here's where i'm setting some relationship (chat to message: 1-to-many)
message.chat = chat
chat.lastMessage = message
message.chat?.lastMessage = message
do {
try context.save()
} catch let err {
print("failed to save private chat:", err)
}
}
The chat ManagedObject has an attribute of lastMessage which is of type Message (also a managed object), i set the newly created message to the Chat's last message. Could the problem be from there.
And here is the delegate code as well:
// MARK: - NSFetchedResultsController Delegates
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
case .delete:
tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
case .move:
break
case .update:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .right)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.moveRow(at: indexPath!, to: newIndexPath!)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
Note that your handling of moving rows (.move) only moves one row, you should implement it to move many. Not sure if this solves your problem, it depends on how your data is sorted.
Here is how I have implemented my .move
case .move:
if let indexPath = indexPath {
tableView.removeRows(at: IndexSet(integer: indexPath.item), withAnimation: .effectFade)
}
if let newIndexPath = newIndexPath {
tableView.insertRows(at: IndexSet.init(integer: newIndexPath.item), withAnimation: .effectFade)
}
Im getting user's input and creating CoreData entity for it, and put in to the tableView, but before i need to designate some properties for entity by making a couple network requests. And there is a problem. First entity is always nil (and create a empty cell for table view) but if i save context and open app again - here it is, entity is ok. If i create second (and so on) entity it works fine. Its also seems like table always create am empty cell for start and then delete it and create proper cell…
I cant get why completion handlers doesn't work properly and network requests makes asynchronously. Please help me to understand.
Creation metod starts in textFieldShouldReturn
import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate {
var managedObjectContext: NSManagedObjectContext?
lazy var fetchedResultsController: NSFetchedResultsController<Word> = {
let fetchRequest: NSFetchRequest<Word> = Word.fetchRequest()
let createdSort = NSSortDescriptor(key: "created", ascending: false)
let idSort = NSSortDescriptor(key: "id", ascending: false)
fetchRequest.sortDescriptors = [createdSort, idSort]
var fetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: AppDelegate.viewContext,
sectionNameKeyPath: nil,
cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
private var hasWords: Bool {
guard let fetchedObjects = fetchedResultsController.fetchedObjects else { return false }
return fetchedObjects.count > 0
}
let creator = WordManager.shared
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
managedObjectContext = AppDelegate.viewContext
fetchWords()
updateView()
}
func updateView() {
tableView.isHidden = !hasWords
messageLabel.isHidden = hasWords
}
............
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let managedObjectContext = managedObjectContext else { return false }
guard let title = textField.text, !title.isEmpty, !title.hasPrefix(" ") else {
showAllert(title: "Warning!", message: "Title may not to be nil!")
return false
}
let word = Word(context: managedObjectContext)
guard let fetchedWordsCount = fetchedResultsController.fetchedObjects?.count else { return false }
creator.createWord(title: title, counter: fetchedWordsCount, word: word)
self.updateView()
textField.text = nil
return true
}
func fetchWords() {
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Cant fetch words. Error \(error.localizedDescription)")
}
}
}
Creating entity
import CoreData
import UIKit
class WordManager {
static var shared = WordManager()
private init() {}
private var api = DictionaryAPI()
private var api2 = MeaningAPI()
func createWord(title: String, counter: Int, word: Word) {
self.api.fetch(word: title, completion: { translation in
self.api2.fetchTranscription(word: title, completion: { transcription in
word.id = Int16(counter) + 1
word.title = title
word.translation = translation
word.transcription = "[\(transcription)]"
word.created = NSDate()
})
})
}
}
Nothing interesting in tableView
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
guard let sections = fetchedResultsController.sections else { return 0 }
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = fetchedResultsController.sections?[section] else { return 0 }
return section.numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mainCell", for: indexPath) as! MainCell
let word = fetchedResultsController.object(at: indexPath)
cell.configure(with: word)
return cell
}
}
Configure cell method
func configure(with word: Word) {
titleField.text = word.title
translationField.text = word.translation
transcriptionLabel.text = word.transcription
totalCounter.text = "\(word.showCounter)"
correctCounter.text = "\(word.correctCounter)"
wrongCounter.text = "\(word.wrongCounter)"
}
Fetched Results Delegate
extension ViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
updateView()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
guard let indexPath = indexPath else { return }
tableView.deleteRows(at: [indexPath], with: .fade)
case .insert:
guard let indexPath = newIndexPath else { return }
tableView.insertRows(at: [indexPath], with: .fade)
case .move:
guard let indexPath = indexPath else { return }
tableView.deleteRows(at: [indexPath], with: .fade)
guard let newIndexPath = newIndexPath else { return }
tableView.insertRows(at: [newIndexPath], with: .fade)
default:
break
}
}
}
Problem:
The data you have in core data is not in a state that is ready to be shown in the app.
The NSFetchedResultsController just happens to pick this data and shows it in the app.
Approach:
When a user creates a records, the user wants to see the changes immediately in the app and shouldn't have to wait for the app to update in the server to see the changes. So a user would still be able to create records even when there is no network connectivity.
Create a child context from view context
Use a background thread to upload to the server and when update records on to the child context.
Save child context only when the data is in a consistent state.
NSFetchedResultsController should be using the view context so would be unaware of the child context records.
When you save the child context, the NSFetchedResultsController would pick these records.
Thanks for considering to help me! so I am getting this error in the console, How should I start going about fixing it?
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext'
*** First throw call stack:
(0x183ff51b8 0x182a2c55c 0x18630cb90 0x1000f4eb0 0x1000f46e8 0x1000f43c8 0x1000f411c 0x1000f40e4 0x101189218 0x10118a048 0x1000f41b4 0x1000fbb94 0x1000fbc94 0x189eaa924 0x189eaa4ec 0x18a2354e4 0x18a1fc6d0 0x18a1f8b44 0x18a13bfdc 0x18a12dd50 0x189e9d0b4 0x183fa20c0 0x183f9fcf0 0x183fa0180 0x183ece2b8 0x185982198 0x189f157fc 0x189f10534 0x1000f69d0 0x182eb15b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
These are the two swift files relevant to my error:
EntryController.swift
import Foundation
import CoreData
class EntryController {
static let shared = EntryController()
var fetchResultsController: NSFetchedResultsController<Entry>
init() {
let request: NSFetchRequest<Entry> = Entry.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "timestamp", ascending: true)
request.sortDescriptors = [sortDescriptor]
fetchResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: CoreDataStack.context, sectionNameKeyPath: nil, cacheName: nil)
(try? fetchResultsController.performFetch())
}
//CRUD
func add(name: String, text: String) {
_ = Entry(name: name, text: text)
saveToPersistanceStorage()
}
func remove(entry: Entry) {
let moc = CoreDataStack.context
moc.delete(entry)
saveToPersistanceStorage()
}
func update(entry: Entry, name: String, text: String) {
entry.name = name
entry.text = text
saveToPersistanceStorage()
}
func saveToPersistanceStorage() {
let moc = CoreDataStack.context
(try? moc.save())
}
}
EntryTableListViewController.swift
import UIKit
import CoreData
class EntrylistTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
EntryController.shared.fetchResultsController.delegate = self
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let entries = EntryController.shared.fetchResultsController.fetchedObjects else {return 0}
return entries.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "entryCell", for: indexPath)
let entry = EntryController.shared.fetchResultsController.object(at: indexPath)
cell.textLabel?.text = entry.name
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let entry = EntryController.shared.fetchResultsController.object(at: indexPath)
EntryController.shared.remove(entry: entry)
}
}
//MARK: NSFetchedResultsControllerDelegate
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
guard let newIndexPath = newIndexPath else {return}
tableView.insertRows(at: [newIndexPath], with: .automatic)
case .delete:
guard let indexPath = indexPath else {return}
tableView.deleteRows(at: [indexPath], with: .automatic)
case .move:
guard let indexPath = indexPath, let newIndexPath = newIndexPath else {return}
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.insertRows(at: [newIndexPath], with: .automatic)
case .update:
guard let indexPath = indexPath else {return}
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetailSegue" {
if let detailVC = segue.destination as? EntryDetailViewController,
let selectedRow = tableView.indexPathForSelectedRow {
let entry = EntryController.shared.fetchResultsController.object(at: selectedRow)
detailVC.entry = entry
}
}
}
}
The app creates that error as soon as the button is pressed from the main menu to segue into the EntryTableListViewController.swift. Any help will be greatly appreciated!
Additionally, here's my CoreDataStack code
import Foundation
import CoreData
enum CoreDataStack{
static let container: NSPersistentContainer = {
let appName = Bundle.main.object(forInfoDictionaryKey: (kCFBundleNameKey as String)) as! String
let container = NSPersistentContainer(name: appName)
container.loadPersistentStores() { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
static var context: NSManagedObjectContext { return container.viewContext }
}
I have a very basic NSFetchedResultsController that shows the data to the user in a UITableView, allows the user to add a new entity and so forth.
However, whenever I add a new entity, my app crashes (or sometimes just warns) with the following message:
CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of sections. The number of sections contained in the table view after the update (3) must be equal to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted). with userInfo (null)
Notice that even thought the numberOfRows have been updated from 2 to 3, the insertion/deletion thing still says (0 inserted, 0 deleted). So my best understanding is that the NSFetchedResultsController is not noticing the changes or something.
My code for NSFetchedResultsController is:
func fetch(frcToFetch: NSFetchedResultsController) {
do {
try frcToFetch.performFetch()
} catch {
return
}
}
func fetchRequest() -> NSFetchRequest {
// Initialize Fetch Request
let fetchRequest = NSFetchRequest(entityName: "ItemInfo")
// Add Sort Descriptors
let nameSortDescriptor = NSSortDescriptor(key: "iName", ascending: true)
fetchRequest.sortDescriptors = [nameSortDescriptor]
return fetchRequest
}
func getFRC() -> NSFetchedResultsController {
if let context = self.context{
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: context, sectionNameKeyPath: "iName.stringGroupByFirstInitial", cacheName: nil)
fetchedResultsController.delegate = self
}
return fetchedResultsController
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch (type) {
case .Insert:
if let indexPath = newIndexPath {
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
break;
case .Delete:
if let indexPath = indexPath {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
break;
case .Update:
if let indexPath = indexPath {
let cell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
configureCell(cell, atIndexPath: indexPath)
}
break;
case .Move:
if let indexPath = indexPath {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
if let newIndexPath = newIndexPath {
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
}
break;
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let sections = fetchedResultsController.sections {
return sections.count
}
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections = fetchedResultsController.sections {
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
return 0
}
And the code to insert new record is:
let entity: NSEntityDescription.entityForName("ItemInfo", inManagedObjectContext: self.context!)!
let record = NSManagedObject(entity: entity, insertIntoManagedObjectContext: self.context!)
record.setValue(name, forKey: "iName")
record.setValue(self.billingMode.text, forKey: "iBillingMode")
do {
// Save Record
try record.managedObjectContext?.save()
try self.context!.save()
// Dismiss View Controller
dismissViewControllerAnimated(true, completion: nil)
} catch {
let saveError = error as NSError
print("\(saveError), \(saveError.userInfo)")
// Show Alert View
showAlertWithTitle("Unexpected Error", message: "Your data could not be saved. Please try again later.", cancelButtonTitle: "Done")
}
Note that the self.context variable is passed from the actual or master view controller that has the NSFetchedResultsController.
Note that the problem is with the number of sections not the number of rows. You need to implement:
(void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo