如何将核心数据的数据迁移到应用组的数据 [英] How to Migrate Core Data's Data to App Group's Data
问题描述
我刚刚使用 StackOverFlow帖子将App Groups
添加到了我的应用程序中.不幸的是,由于defaultDirectoryURL
发生了变化,因此在使用App Groups目录之前,我无法获取我制作的任何旧数据.我知道数据仍然存在,因为当我切换回使用常规的NSPersistentContainer
而不是GroupedPersistentContainer
时,可以获得数据.
I just added App Groups
to my app using this StackOverFlow post. Unfortunately since the defaultDirectoryURL
is changing, I can not fetch any of the old data I made before using the App Groups directory. I know the data is still there because when I switch back to using a regular NSPersistentContainer
instead of the GroupedPersistentContainer
, I can get the data.
如何将旧数据迁移到获取应用程序组数据的位置?
How can I migrate my old data over to where I'm fetching the app group's data?
核心数据代码:
class CoreDataManager {
static let sharedManager = CoreDataManager()
private init() {}
lazy var persistentContainer: NSPersistentContainer = {
var useCloudSync = UserDefaults.standard.bool(forKey: "useCloudSync")
let containerToUse: NSPersistentContainer?
if useCloudSync {
containerToUse = NSPersistentCloudKitContainer(name: "App")
} else {
containerToUse = GroupedPersistentContainer(name: "App")
let description = containerToUse!.persistentStoreDescriptions.first
description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
}
guard let container = containerToUse, let description = container.persistentStoreDescriptions.first else {
fatalError("Hey Listen! ###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
...
return container
}
}
GroupedPersistentContainer代码:
class GroupedPersistentContainer: NSPersistentContainer {
enum URLStrings: String {
case group = "group.App"
}
override class func defaultDirectoryURL() -> URL {
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: URLStrings.group.rawValue)
if !FileManager.default.fileExists(atPath: url!.path) {
try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
}
return url!
}
}
我还没有为我的NSPersistentCloudKitContainer做到这一点,但是它将遵循与此格式相同的格式.
I haven't done this yet for my NSPersistentCloudKitContainer yet but it will follow the same format as this one.
推荐答案
import UIKit
import CoreData
class GroupedPersistentContainer: NSPersistentContainer {
override open class func defaultDirectoryURL() -> URL {
var storeURL = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.YourApp")
.unsafelyUnwrapped
storeURL = storeURL.appendingPathComponent("YourApp.sqlite")
return storeURL
}
}
另请参阅: 使用核心数据共享数据:iOS应用和扩展程序
这篇关于如何将核心数据的数据迁移到应用组的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!