【问题标题】:Migrate local Core Data Store to iCloud for existing project with Swift使用 Swift 将本地 Core Data Store 迁移到 iCloud 以用于现有项目
【发布时间】:2015-10-19 09:25:18
【问题描述】:

我想为现有项目启用 iCloud for Core Data。用户可以使用新 iPhone 或其他 iPhone 上的应用程序来处理他的旧数据。所以我必须将可能存在的商店迁移到 iCloud/无处不在的容器中的新商店。

当您使用 iOS 8 创建新的 Swift 项目时,我添加了 iCloud 文档功能并使用 Apple 提供的默认核心数据堆栈模板。

Apple 核心数据堆栈模板:

    lazy var applicationDocumentsDirectory: NSURL = {
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1] as! NSURL
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("testapp", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("testapp.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext? = {
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext()
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if let moc = self.managedObjectContext {
        var error: NSError? = nil
        if moc.hasChanges && !moc.save(&error) {
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
    }
}

我在苹果开发者那里读到了关于函数 migratePersistentStore 和在 StackOverflow 上关于答案 Move local Core Data to iCloud 的信息,但我不知道如何在该模板中正确实现这一点。

根据我的理解,我认为,如果 url 指向现有的商店/文件,我必须检查协调器的惰性 var 定义。如果是这样,我必须使用函数 migratePersistentStore:xmlStore 和选项 NSPersistentStoreUbiquitousContentNameKey 迁移到新商店。

于是我写了一个新的持久化协调器:

迁移持久性协调员

   lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    // create new iCloud-ready-store
    let iCloudStoreUrl = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TestAppiCloud.sqlite")
    var iCloudOptions: [NSObject : AnyObject]? = [
        NSPersistentStoreFileProtectionKey: NSFileProtectionComplete,
        NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true,
        NSPersistentStoreUbiquitousContentNameKey: "TestAppiCloudStore"
    ]

    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."

    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: iCloudStoreUrl, options: iCloudOptions, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    // Possible old store migration

    let existingStoreUrl = self.applicationDocumentsDirectory.URLByAppendingPathComponent("testapp.sqlite")
    let existingStorePath = existingStoreUrl.path

    // check if old store exists, then ...
    if NSFileManager.defaultManager().fileExistsAtPath(existingStorePath!) {
        // ... migrate
        var existingStoreOptions = [NSReadOnlyPersistentStoreOption: true]
        var migrationError: NSError? = nil

        var existingStore = coordinator!.persistentStoreForURL(existingStoreUrl)
        coordinator!.migratePersistentStore(existingStore!, toURL: iCloudStoreUrl, options: existingStoreOptions, withType: NSSQLiteStoreType, error: &migrationError)
    }

    // iCloud Notifications
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self,
        selector: "storeWillChange",
        name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
        object: coordinator!)
    notificationCenter.addObserver(self,
        selector: "storeDidChange",
        name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
        object: coordinator!)
    notificationCenter.addObserver(self,
        selector: "storeDidImportUbiquitousContentChanges",
        name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
        object: coordinator!)

    return coordinator
    }()

但是当迁移从 coordinator!.migratePersistentStore 开始时,我遇到了一个异常:

var existingStore = coordinator!.persistentStoreForURL(existingStoreUrl) // 无

但文件管理器说,它存在!

我做错了什么?这个想法正确吗?请帮忙。

【问题讨论】:

  • 嗨,你找到答案了吗?
  • 是的,我找到了解决方案。但这不好,可能会在appstore更新后丢弃用户数据库。

标签: swift core-data icloud database-migration


【解决方案1】:

我遇到了与“persistentStoreForURL”完全相同的问题。事实证明,我一直在寻找类似“persistenStoreWITHurl”的东西。我错误地假设它实际上会加载商店,但事实证明,它没有。当商店已经加载到协调器中时,此功能起作用。我知道你刚才问过这个问题,但我会把这个留在这里,以防其他人遇到同样的问题。因此,更改代码将使其按预期工作:

    let coordinator = self.persistentStoreCoordinator
    let existingStore = coordinator.persistentStores.first

    var options = Dictionary<NSObject, AnyObject>()
    options[NSPersistentStoreRemoveUbiquitousMetadataOption] = true
    options[NSMigratePersistentStoresAutomaticallyOption] = true
    options[NSInferMappingModelAutomaticallyOption] = true


    do {
         try coordinator?.migratePersistentStore(existingStore!, to: url2, options: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true], withType: NSSQLiteStoreType)

    }
    catch {

        print(error)

    }

【讨论】:

  • 这非常有效。它需要以下更新:尝试 coordinator?.migratePersistentStore(existingStore!, to: url2, options: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true], withType: NSSQLiteStoreType)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多