Search code examples
core-dataswiftui

Having trouble finding my core-data file on my macbook


I'm running my app using Xcode 12.4 and I'm using persisting my data using Core Data. When I try to fetch the data and print it inside of a list, it prints the data correctly, but I'm having trouble finding the actual DB file on my mac.

Normally I would run print("Documents Directory: ", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found!")and that would lead me to the correct file, but when I go to the destination now, the documents folder is empty.

Any ideas how I can retrieve the file?


Solution

  • If you're using NSPersistentContainer, try asking the container for the path it's using. You can do this any time after calling loadPersistentStores(completionHandler:):

    print("Path to store file: \(container.persistentStoreCoordinator.persistentStores.first?.url?.path ?? "not found")")
    

    Or you can put this in the completion closure you pass to loadPersistentStores(completionHandler:):

    print("Loaded persistent store at \(storeDescription.url!.path)")
    

    Keep in mind that the path will change every time you run the app, so be sure you have the current path. There are a couple of UUIDs in the path-- one of them doesn't change unless you delete the app, but the other changes all the time. For example once it might be this (wrapped here for readability)

    /Users/[you]/Library/Developer/CoreSimulator/Devices/
        445F0055-2A61-478A-9BA9-7F44CE038242/data/Containers/Data/Application/
        4B21151B-4148-470B-88AC-F323CB88434D/Library/
        Application Support/[AppName].sqlite
    

    Then the next time it's this

    /Users/[you]/Library/Developer/CoreSimulator/Devices/
        445F0055-2A61-478A-9BA9-7F44CE038242/data/Containers/Data/Application/
        E8889B57-41CB-4F14-AAB2-A02142DC47FF/Library/
        Application Support/[AppName].sqlite
    

    Which is kind of a pain, but you do need to check it every time.