【发布时间】:2016-08-26 03:28:18
【问题描述】:
最近将核心数据堆栈实现从应用程序委托移动到不同的类是一种做法。在大多数实现中,我看到核心数据堆栈继承自 NSObject,即使在 Apple 的文档中也是如此。
- 有什么原因吗?没有它似乎也能工作。
- 为什么 Apple 的 init 方法不调用 super.init() 不是必须的吗?
import UIKit
import CoreData
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
init() {
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = NSBundle.mainBundle().URLForResource("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(contentsOfURL: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = psc
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}
}
}
}
【问题讨论】:
-
“将核心数据堆栈实现从应用程序委托移动到不同的类是一种做法”谁的做法?能举个例子吗?
-
当然,我添加了 Apple 的 CDS 代码示例,即 DataController
-
项目模板也是这样的吗?他们是否使用与 AppDelegate 不同的 DataController 对象?
-
你指的是哪个项目?
-
创建新项目时的任何 Core Data 模板。