简体   繁体   English

Swift-用iCloud核心数据替换核心数据

[英]Swift - Replace Core Data with iCloud Core Data

How to replace my exsisting Core Data with iCloud Core Data ? 如何用iCloud核心数据替换现有的核心数据? This is my persistentStoreCoordinator: 这是我的persistentStoreCoordinator:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    var notificacionCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter()
    notificacionCenter.addObserver(self, selector: "storesWillChange:", name:NSPersistentStoreCoordinatorStoresWillChangeNotification, object: coordinator)
    notificacionCenter.addObserver(self, selector: "storesDidChange:", name:NSPersistentStoreCoordinatorStoresDidChangeNotification, object: coordinator)
    notificacionCenter.addObserver(self, selector: "persistentStoreDidImportUbiquitousContentChanges:", name:NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: coordinator)

    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyApp.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    var options: NSDictionary = [NSMigratePersistentStoresAutomaticallyOption : NSNumber(bool: true), NSInferMappingModelAutomaticallyOption : NSNumber(bool: true),
        NSPersistentStoreUbiquitousContentNameKey : "iCloudStore"]
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, 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)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    return coordinator
}()

I add notifications and then what? 我添加通知,然后呢? How to replace it ? 如何更换呢?

You don't need to do anything to have the iCloud stored data replace the local stored data. 您无需执行任何操作即可将iCloud存储的数据替换为本地存储的数据。 That is, the local Core Data is updated with the iCloud-downloaded data and kept consistent thereafter, behind your back. 也就是说,本地iCore数据会使用iCloud下载的数据进行更新,并在此之后保持一致,而无需担心。

However, if you have displayed data in your UI then the 'old local data' might still be displayed when the 'new iCloud data' arrives. 但是,如果您已经在UI中显示了数据,那么当“新iCloud数据”到达时,“旧本地数据”可能仍会显示。 The Apple documentation at Using the SQLite Store with iCould describes how to handle the updates though the notifications. 与iCould一起使用SQLite商店中的Apple文档介绍了如何通过通知处理更新。 Summarizing that reference: in the handler for NSPersistentStoreCoordinatorStoresWillChangeNotification you save any pending changes if they exist otherwise you reset the managed object context and disable the user interface. 总结一下该引用:在NSPersistentStoreCoordinatorStoresWillChangeNotification的处理程序中,如果存在任何未决的更改,则将它们保存,否则将重置托管对象上下文并禁用用户界面。 Then in the NSPersistentStoreCoordinatorStoresDidChangeNotification handler your update your displayed (and other) data and reenable your UI. 然后,在NSPersistentStoreCoordinatorStoresDidChangeNotification处理程序中,更新显示的数据(和其他数据)并重新启用UI。

This is what I've used for Core Data w/ iCloud. 这就是我用于带iCloud的Core Data的功能。 The storeOptions is the key point. storeOptions是关键。 For your Xcode target you need to enable the iCloud capability and ensure that you've selected 'iCloud Documents'. 对于Xcode目标,您需要启用iCloud功能并确保已选择“ iCloud文档”。

{
  // ...

  lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation
    // creates and return a coordinator, having added the store for the 
    // application to it. This property is optional since there are legitimate
    // error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator =
      NSPersistentStoreCoordinator (managedObjectModel: self.managedObjectModel)

    var storeURL =
      self.applicationDocumentsDirectory
        .URLByAppendingPathComponent("iAppSwift.sqlite")

    var storeOptions =
      [NSPersistentStoreUbiquitousContentNameKey : "iAppSwiftStore"
      // NSPersistentStoreRebuildFromUbiquitousContentOption: @(true)
        ]

    // 
    self.registerCoordinatorForStoreNotifications (coordinator)

    var error : NSError? = nil
    var store : NSPersistentStore! =
      coordinator.addPersistentStoreWithType (NSSQLiteStoreType,
        configuration: nil,
        URL: storeURL,
        options: storeOptions,
        error: &error)

    if nil == store {
      // handle error
    }

    return coordinator
  }()

  func registerCoordinatorForStoreNotifications (coordinator : NSPersistentStoreCoordinator) {
    let nc : NSNotificationCenter = NSNotificationCenter.defaultCenter();

    nc.addObserver(self, selector: "handleStoresWillChange:",
      name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
      object: coordinator)

    nc.addObserver(self, selector: "handleStoresDidChange:",
      name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
      object: coordinator)

    nc.addObserver(self, selector: "handleStoresWillRemove:",
      name: NSPersistentStoreCoordinatorWillRemoveStoreNotification,
      object: coordinator)

    nc.addObserver(self, selector: "handleStoreChangedUbiquitousContent:",
      name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
      object: coordinator)
  }

  // ...
}

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

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