3lvis / DATAStack

100% Swift Simple Boilerplate Free Core Data Stack. NSPersistentContainer
Other
214 stars 44 forks source link

How to use two stack instances with the same model? #105

Closed katunch closed 5 years ago

katunch commented 7 years ago

Hi I've got the following model (for example) screen shot 2017-06-15 at 18 18 14

Then in my controller i define the data stack like this:

let coreData = DATAStack(modelName: "Test", storeType: .sqLite)

Later I'd like to do a count on the Product entity like this:

        do {
            let productCount = try coreData.viewContext.count(for: Product.fetchRequest())
            debugPrint("product Count in coredata: \(productCount)")
        }
        catch let e {
            debugPrint(e.localizedDescription)
        }

That works as expected!

Now I'd like to do some kind of archive with the exact same model. So what I did is to just create another instance with the same model like this:

let archive = DATAStack(modelName: "Test", bundle: Bundle.main, storeType: .sqLite, storeName: "Test-Archive", containerURL: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!)

After that the productCount will not work anymore and the app crashes with the following message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '_countWithNoChangesForRequest:error: A fetch request must have an entity.

Here is the whole code to reproduce this behaviour:

import UIKit
import DATAStack

class ViewController: UIViewController {

    let coreData = DATAStack(modelName: "Test", storeType: .sqLite)
    let archive = DATAStack(modelName: "Test", bundle: Bundle.main, storeType: .sqLite, storeName: "Test-Archive", containerURL: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!)

    override func viewDidLoad() {
        super.viewDidLoad()

        debugPrint("coreData located at: \(coreData.viewContext.persistentStoreCoordinator!.persistentStores.first!.url!.absoluteString)")
        debugPrint("archive located at: \(archive.viewContext.persistentStoreCoordinator!.persistentStores.first!.url!.absoluteString)")

        do {
            let productCount = try coreData.viewContext.count(for: Product.fetchRequest())
            debugPrint("product Count in coredata: \(productCount)")
        }
        catch let e {
            debugPrint(e.localizedDescription)
        }
    }

}

Can anyone help me with this one? How can I approach this? Thx

3lvis commented 5 years ago

Closing since this issue seems outdated.