当NSPersistentStoreCoordinator.addPersistentStore随机

时间:2019-10-28 01:35:02

标签: ios

在应用程序(_:didFinishLaunchingWithOptions:)->布尔。我编写代码初始化CoreData,在应用程序组目录中创建一个sqlite文件。 在开发和测试中一切正常。当我将App发布到AppStore时,我收到一些有关崩溃的报告。

NSFilePath = / private / var / mobile / Containers / Shared / AppGroup / 979F9001-AFCB-4BA2-BDDF-0CF816BA38C3 / Documents / db.sqlite,reason =路径/ private / var / mobile / Containers / Shared / AppGroup / 979F9001-AFCB-4BA2-BDDF-0CF816BA38C3 / Documents / db.sqlite不是目录

它是随机发生的,可能性很小。

我不知道为什么...也许在didFinishLaunchingWithOptions何时未准备好应用程序组?如何解决...

func prepareDatabase()throws { 
    let dirURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.my.app")!
    let document = dirURL.appendingPathComponent("Documents")
    if FileManager.default.fileExists(atPath: document.path) == false {
        try! FileManager.default.createDirectory(at: document, withIntermediateDirectories: true, attributes: nil)
    }
    let storeURL = dirURL.appendingPathComponent("db.sqlite")
    guard let modelURL = Bundle.main.url(forResource: "db", withExtension: "momd") else {
        throw AppError.GuardError(with: "can't find db.momd")
    }
    guard let model : NSManagedObjectModel = NSManagedObjectModel(contentsOf: modelURL) else {
        throw AppError.GuardError("NSManagedObjectModel can not create by file at \(modelURL)")
    }
    let coordinator : NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
    let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]
    try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) // I think the problem is here
    let context = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    context.persistentStoreCoordinator = coordinator
    context.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
}

0 个答案:

没有答案