【问题标题】:Should Core Data Stack inherit from NSObject and why?Core Data Stack 应该从 NSObject 继承吗?为什么?
【发布时间】:2016-08-26 03:28:18
【问题描述】:

最近将核心数据堆栈实现从应用程序委托移动到不同的类是一种做法。在大多数实现中,我看到核心数据堆栈继承自 NSObject,即使在 Apple 的文档中也是如此。

  1. 有什么原因吗?没有它似乎也能工作。
  2. 为什么 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)")
            }
        }
    }
}

Initializing the Core Data Stack

【问题讨论】:

  • “将核心数据堆栈实现从应用程序委托移动到不同的类是一种做法”谁的做法?能举个例子吗?
  • 当然,我添加了 Apple 的 CDS 代码示例,即 DataController
  • 项目模板也是这样的吗?他们是否使用与 AppDelegate 不同的 DataController 对象?
  • 你指的是哪个项目?
  • 创建新项目时的任何 Core Data 模板。

标签: ios swift core-data


【解决方案1】:

理论上堆栈可以存在于任何对象中,而在 Swift 中,该对象不需要从 NSObject 派生。但实际上,它还需要是一个对所有代码全局可用的单例,并且奥卡姆剃刀和时间的要求总是使应用程序委托成为一个明显的轨迹,因为它完美地满足了该描述,尤其是当你从 Core Data 模板创建一个新项目。

为什么苹果的init方法不调用super.init()不是必须的吗?

它是由 Swift 自己自动完成的。

【讨论】:

  • 但我鼓励您实现单例并正确执行此操作。当你这样做时,在 Swift 中就不需要从 NSObject 派生了。
  • "它是由 Swift 自己自动完成的。"你怎么知道的?
  • 我可以看到它正在发生,使用符号断点。它也有据可查here。另外,Apple 的某个人直接告诉了我。我有一个针对它的错误,因为我不喜欢这种秘密行为。
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 2011-10-28
  • 1970-01-01
  • 2019-02-18
  • 2019-09-24
  • 2012-10-23
  • 2010-12-12
  • 1970-01-01
相关资源
最近更新 更多