如何设置PersistantStore

时间:2017-03-03 09:19:34

标签: ios swift xcode core-data

我喜欢应用程序和今天的扩展中的核心数据。但是,我的实体总是空的。我猜网址存在一些问题。

所以,我检查一下我的目录。然后我可以检查我的文档状态是否已关闭。文件已存在。但是,我无法真正开放。我怎么打开它?

这是自定义核心dat类中的核心数据方法:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel:
        self.managedObjectModel)
    let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group....")

    let url = directory!.appendingPathComponent("name.sqlite")

    let document = UIManagedDocument(fileURL: url)

    if document.documentState == .normal {
        NSLog("document is normal status")
    }

    if document.documentState == .closed {

        let fileExist = FileManager.default.fileExists(atPath: url.path)
        NSLog("fileExist =\(fileExist)")

        document.open(completionHandler: { (success: Bool) in
            if success {
                NSLog("document is opened!")
            }else {
                NSLog("document is still clodsed!")
                return
            }
        })

        NSLog("document is closed")
    }


    do {
        try coordinator.addPersistentStore(ofType:
            NSSQLiteStoreType,
                                           configurationName: nil,
                                           at: url,
                                           options: nil)
    } catch {
        // Report any error we got.
        NSLog("CoreData error \(error), \(error._userInfo)")
        self.errorHandler(error)
    }
    return coordinator
}()

这是日志:

fileExist =true
document is closed
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIManagedDocument can only read documents that are file packages'

是否正确访问?

2 个答案:

答案 0 :(得分:1)

您不需要UIManagedDocument

let baseUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group....")

var storeUrl = baseUrl.appendingPathComponent(momdName)
storeUrl = storeUrl.appendingPathExtension("sqlite")

...

try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeUrl, options: nil)

...

答案 1 :(得分:0)

试试这个:

let fm = FileManager.default
if let docsDir = fm.urls(for: .documentDirectory, in: .userDomainMask).first {
            let url = docsDir.appendingPathComponent("MyDocumentName")
            let document = UIManagedDocument(fileURL: url)

            if document.documentState == .normal {

            } else if document.documentState == .closed {
                if fm.fileExists(atPath: url.path) {
                    document.open(completionHandler: { (success) in

                    })
                } else {
                    document.save(to: document.fileURL, for: .forCreating, completionHandler: { (success) in

                    })
                }
            }
        }