简体   繁体   English

Swift-如何检查现有的Core Data Store iOS

[英]Swift - how to check for existing Core Data Store iOS

I'm working on an app that should have a starting window that will have an intro and then either a "Get Started" button if no existing core data store is found, and then if a store is present - it should have a "Continue Session" and "Start Over" buttons. 我正在开发一个应具有启动窗口的应用程序,该窗口将有一个简介,然后,如果未找到现有的核心数据存储,则显示一个“ Get Started”按钮,然后,如果存在一个存储,则应显示一个“ Continue”会话”和“重新开始”按钮。 Only problem I don't think my code for checking for a store is working - I'm putting this in the ViewController's viewDidLoad function: 唯一的问题是我认为我检查商店的代码不起作用-我将其放在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
    }

So all I'm getting is "can't find store" - even after running the app a few times. 因此,我得到的只是“找不到商店”-即使在运行该应用几次之后。 I've navigated to \\Library\\Developer\\CoreSimulator\\Devices\\blahblah\\data\\Containers\\Data\\Application\\blahblah\\Documents and do see my "LearnUSStateCapitals.sqlite" file there created at the time I first ran the app as is... 我导航到\\Library\\Developer\\CoreSimulator\\Devices\\blahblah\\data\\Containers\\Data\\Application\\blahblah\\Documents并确实看到了我第一次按原样运行该应用程序时在其中创建的“ LearnUSStateCapitals.sqlite”文件。 ..

The reason I'm using if defaultStorePath == nil is because when I try if fileManager.fileExistsAtPath(defaultStorePath!) I get unexpectedly found nil while unwrapping an Optional value - why is this nil maybe the real question... thanks for any help if defaultStorePath == nil使用if defaultStorePath == nil的原因是因为当我尝试if fileManager.fileExistsAtPath(defaultStorePath!) unexpectedly found nil while unwrapping an Optional value为什么这个nil可能是真正的问题...感谢您的任何帮助

The file you can see is in the Application Documents directory, which is different from the main bundle. 您可以看到的文件位于“应用程序文档”目录中,与主捆绑包不同。 You can get a URL for the application documents directory with: 您可以使用以下方法获取应用程序文档目录的URL:

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

then use: 然后使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM