【发布时间】:2018-07-21 07:05:01
【问题描述】:
请求更新,因为这个问题当然已经回答了以前的版本,日期为 12/16 的最新搜索结果与以前的 iOS 9 和 10 项目产生了不相关的兼容性。
文档当然说在开始一个新项目时选择使用核心数据复选框,我没有选择,但现在认为需要添加 iCloud + 核心数据才能将我的应用程序带到下一个阶段 -> 其中一些像 NSFileCoordinator 和 NSFilePresenter 是必需的,因为在我的应用程序 UI 中,用户会看到许多主题,每个主题都有三个选项,关于哪些用户将选择一个选项。对于每个主题,UI 会显示选择每个选项的用户总数以及每个选项的总数百分比。
现在,每个选项的选择数量和总数的百分比当然只是在我的本地应用程序中计算 -> 但实际上需要在云等中心或最有可能在网站上计算......但是然后网站提出了 NSFileCoordinator 和 NSFilePresenter 已经解决的同时读/写问题。
因此,如果 iCloud + Core Data 系统可以在发送新的 Ubiquitous Container 数值总数和百分比值之前,在接收到单个用户的写入数值命令后在云中插入基本算术计算- 那么我非常感谢有关如何修复下面在尝试创建和初始化核心数据堆栈时生成的错误的建议。否则我想我将不得不爬取 Xcode 并使用像 PhoneGap 这样的混合应用程序,如果这是最适合这项工作的应用程序的话。
因此,请参阅核心数据编程指南:
并在我现有项目的开头粘贴以下代码,生成
使用未解析的标识符“persistentContainer”...“managedObjectContext”
... 错误。还有那行
init(completionClosure: @escaping () -> ()) {
...生成
初始化器只能在类型中声明
import UIKit
import CoreData
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
init(completionClosure: @escaping () -> ()) {
persistentContainer = NSPersistentContainer(name: "DataModel")
persistentContainer.loadPersistentStores() { (description, error) in
if let error = error {
fatalError("Failed to load Core Data stack: \(error)")
}
completionClosure()
}
}
}
init(completionClosure: @escaping () -> ()) {
//This resource is the same name as your xcdatamodeld contained in your project
guard let modelURL = Bundle.main.url(forResource: "DataModel", withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = psc
let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
queue.async {
guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
fatalError("Unable to resolve document directory")
}
let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
//The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
DispatchQueue.main.sync(execute: completionClosure)
} catch {
fatalError("Error migrating store: \(error)")
}
}
}
// followed by my existing working code:
class ViewController: UIViewController {
【问题讨论】: