swift - 使用 arrayController 结果为 "Cannot perform operation without a managed object context"

标签 swift cocoa core-data nsarraycontroller

我正在用 Swift 2.2 重写我之前的 objC 应用程序。这是 cocoa 应用程序,我使用 NSArrayController 来填充 NSTableView 内容。 尽管类似的设置在 Objective C 应用程序中也有效,但错误很明显。

这是我的 AppDelegate:

 var coreStack:AP_CoreDataStack!
var mainContext:NSManagedObjectContext!

override func awakeFromNib() {
coreStack = AP_CoreDataStack(){ (result) -> () in
        if result {
            self.mainContext = self.coreStack.mainContext
        }
    }
}

核心数据堆栈的设置

// MARK: - AP_CoreDataStack Class
class AP_CoreDataStack {

let mainContext: NSManagedObjectContext
let mastercontext: NSManagedObjectContext
var workerContext: NSManagedObjectContext?


internal typealias CallBack = (result:Bool) -> Void
init ( callback: CallBack) { 


    let modelURL = NSBundle.mainBundle().URLForResource("appNameSWIFT", withExtension: "momd")
    if (modelURL == nil) {
        print("Failed to initialize modelURL: \(modelURL)")
    }

    let mom = NSManagedObjectModel(contentsOfURL: modelURL!)
    if mom == nil {
        print("Failed to initialize model")
    }

    let psc = NSPersistentStoreCoordinator(managedObjectModel: mom!)

    mastercontext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
    mastercontext.persistentStoreCoordinator = psc

    mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    mainContext.parentContext = mastercontext


    // add store to psc in background thread
    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    dispatch_async(backgroundQueue, {
        //BACKGROUND THREAD
        // adding store to persistent store coordinator
        let options = [NSInferMappingModelAutomaticallyOption:true,
            NSMigratePersistentStoresAutomaticallyOption:true]
        do {
            // store = try psc.addP
            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: applicationDocumentDirectory(), options: options)
        } catch let error as NSError {
            print("Error: Failed to load store \(error.localizedDescription), \(error.userInfo)")
        }

        // MAIN THREAD
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            // On Main thread pass message that stack setup is complete
            callback(result: true)
        })
    })


}

上面是我的 Obj C 代码的 Swift 版本,运行良好。我在 xib 文件中有一个 NSArrayController ,它绑定(bind)到 IB 中的 Entity 和 NSManagedObjectContext :

// Bind To Delegate
self.mainContext

看起来数组 Controller 在初始化之前正在访问 mainContext,但这与 objC 中的设置相同,所以为什么它在 Swift 中导致错误。

编辑:我正在使用常规 xib 文件。

编辑2:

显然 mainContext 不为零,因为在这里调用它可以正常工作

    func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application

    let request = NSFetchRequest(entityName: "AP_EntityA")
    let list:Array<AnyObject>
    do {
        list = try coreStack.mainContext.executeFetchRequest(request)
        for item in list {
            let product = item as! AP_EntityA
           print("item name is: \(product.uniqueName)")
        }
    } catch let error as NSError {
        // failure
        print("Fetch failed: \(error.localizedDescription)")
    }

}

最佳答案

添加 dynamic 关键字以使 Swift 属性符合 KVO 标准。

dynamic var mainContext:NSManagedObjectContext!

关于swift - 使用 arrayController 结果为 "Cannot perform operation without a managed object context",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997265/

相关文章:

iphone - 如何从 iPhone 通过 WiFi 向 Mac 发送命令?

objective-c - 如果两个 ObjC 类别重写同一个方法会怎样?

cocoa - 以编程方式在 WebView 中打开链接

swift - 是否可以只返回核心数据中所需的对象

swift - 显示没有按钮的 UIAlertController 时 UI 测试失败

swift - 如何在同一个 View Controller 中实现多个组合框的数据源

ios - 暂停和恢复 for 循环

ios - 自动代码中的无效重新声明生成 NSManagedObject 子类 Swift 3

core-data - 尝试使用 NSFetchedResultsController 创建 USE_BLOCK_IN_FRAME ... EXC_BAD_ACCESS

ios - 如何将 TableView 动态单元格链接到特定的 View Controller ?