1

I want to add an extension to my iOS app and I want to use the core data I already use in my main application with saved data.

I checked my app and extension on the target Membership for my model and CoreDataManager (my Custom Class for managing Core Data).

First I just tried to run it only with targets checked but I couldn't access my saved data.

Then I enabled app groups and change my class like this:

class CoreDataManager {

    static let shared = CoreDataManager()
    lazy var context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

    init() {
        guard let modelURL = Bundle.main.url(forResource: "CoreDataModel", withExtension: "momd"),
                let model = NSManagedObjectModel(contentsOf: modelURL) else { return }

        context.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)

        _ = try? context.persistentStoreCoordinator?
                            .addPersistentStore(ofType: NSSQLiteStoreType,
                                                configurationName: nil,
                                                at: coreDataUrl(),
                                                options: [NSMigratePersistentStoresAutomaticallyOption: true])
    }

    func saveContext() {
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                print(error)
            }
        }
    }

    private func coreDataUrl() -> URL {
        var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.favorites")
        storeURL = storeURL?.appendingPathComponent("CoreDataModel")
        return storeURL!
    }
}

Now I can access my saved data but only data that I've saved after the implementation I did.

So my question is can I somehow retrieve data that I saved before changing my coredata location?

Thanks in advance

mike vorisis
  • 2,786
  • 6
  • 40
  • 74

0 Answers0