老房东
老房东的纸条箱

老房东的纸条箱

获取CoreData数据存储位置小纸条

Photo by Markus Winkler on Unsplash

获取CoreData数据存储位置小纸条

老房东's photo
老房东
·Apr 19, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

在进行CoreData的开发时,有时你需要知道数据库里到底发生了什么变化,这时就需要了解到CoreData数据到底存到了哪里。这是Xcode自动生成的CoreData初始化部分的代码:

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "testCoreData")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }

在这里,可以通过print storeDescription即可得到存储路径

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "testCoreData")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            // show storePath
            print(storeDescription)
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
 
Share this