Search code examples
iosswiftcore-data

Swift - Unexpected rows added to CoreData


I have a CoreData base with 6 rows in it.

I na ViewController, the data is displayed in a UITable, when I select a row in the table, the didSelectRow lists 6 rows. That are all the rows.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    caches = CoreData.getCaches()
    print ("Amount \(caches.count)") // gives 6

    performSegue(withIdentifier: "Select", sender: nil)
}

When the Segue is executed the prepareForSegue is executed. Now the same command results with the value 7.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    caches = CoreData.getCaches()
    print ("Amount \(caches.count)") // gives 7
}

I suspect that something in the background is happening, but i can't find out what. Below is the static method for reference:

static func getCaches() -> [Caches] {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    var resultArray: [Caches] = []

    let request = NSFetchRequest<Caches>(entityName: "Caches")
    request.returnsObjectsAsFaults = false

    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    let sortDescriptors = [sortDescriptor]
    request.sortDescriptors = sortDescriptors

    do {
        resultArray = try context.fetch(request)
    } catch {
        print("Error - \(error)")
    }
    return resultArray
}

Solution

  • After a lot of searching I found it.

    I execute a performSegueWithIdentifier. Which calls the prepareForSegue in the calling ViewController. But apparently before that, the variables/properties from the called VC are created. (Which is logical if you give it some thought)

    In the called VC, a variable was initialised with the following code (copied from somewhere on the net)

    var cache = Caches((context: (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext))
    

    This line of ode was causing the trouble. Cause it creates an entity in the persistentContainer (not written to the actual CoreData). I replaced it with a plain old:

    var cache = Caches()
    

    And everything is working okay now. Thanks for the support.