【问题标题】:Swift - how to check for existing Core Data Store iOSSwift - 如何检查现有的 Core Data Store iOS
【发布时间】:2015-01-27 20:48:59
【问题描述】:

我正在开发一个应用程序,它应该有一个启动窗口,如果没有找到现有的核心数据存储,则应该有一个启动窗口,然后是“开始”按钮,如果存在存储 - 它应该有“继续会话”和“重新开始”按钮。唯一的问题是,我认为我用于检查商店的代码不起作用 - 我将其放入 ViewController 的 viewDidLoad 函数中:

override func viewDidLoad() {
    super.viewDidLoad()
    let defaultStorePath = NSBundle.mainBundle().pathForResource("LearnUSStateCapitals", ofType: "sqlite")
    let fileManager = NSFileManager.defaultManager()
    if defaultStorePath == nil {
        println("can't find store")
        generateSCA()
    } else {
        println("store found...I think")
        continueButton.hidden = false
    }

所以我得到的只是“找不到商店”——即使在运行了几次应用程序之后也是如此。我已经导航到\Library\Developer\CoreSimulator\Devices\blahblah\data\Containers\Data\Application\blahblah\Documents 并确实看到了我在第一次按原样运行应用程序时创建的“LearnUSStateCapitals.sqlite”文件...

我使用if defaultStorePath == nil 的原因是因为当我尝试if fileManager.fileExistsAtPath(defaultStorePath!) 时,我得到unexpectedly found nil while unwrapping an Optional value - 为什么这个nil 可能是真正的问题...感谢您的帮助

【问题讨论】:

    标签: ios sqlite swift core-data


    【解决方案1】:

    您可以看到的文件位于Application Documents 目录中,该目录与主包不同。您可以通过以下方式获取应用程序文档目录的 URL:

    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    let appDocsURL : NSURL = urls[urls.count - 1] as NSURL
    let defaultStoreURL = appDocsURL.URLByAppendingPathComponent("LearnUSStateCapitals.sqlite")
    

    然后使用:

    if !fileManager.fileExistsAtPath(defaultStoreURL.path!) {
        println("can't find store")
        generateSCA()
    } else {
        println("store found...I think")
        continueButton.hidden = false
    }
    

    【讨论】:

    • 太棒了 - 这很有效 - 非常感谢,但这是否意味着我的商店在错误的地方 - 我没有使用基于“文档”的应用程序......无论如何也不是故意的。
    • 您的数据库位于正确的位置 - Documents 目录旨在用于最松散意义上的应用程序“文档” - 几乎所有应用程序数据都应该放在那里(或它的子目录)。事实上,主包是只读的。
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 2015-05-15
    • 2015-10-19
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多