如何在Swift 4和Xcode 10中将ArrayController绑定到managedObjectContext

时间:2019-01-10 10:47:57

标签: swift xcode binding nsarraycontroller managedobjectcontext

我是Xcode | swift | binding | persistentContainers的新手。我正在学习如何使用Swift 4和Xcode 10创建coreData应用程序。

在参加在线培训课程时,我一直试图将NSArrayController的ManagedObjectContext(MOC)绑定到主MOC。当我尝试进行绑定时,我只会看到两个选项: 1. ViewController 2. SharedUserDefaultsController

我尝试将下面插入的代码添加到viewController中,以获取MOC的所有权,但无济于事。我已经尝试了很多事情,但是一直失败。

import Cocoa

class ViewController: NSViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    var context: NSManagedObjectContext?


    if #available(iOS 10.0, *) {
        context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    } else {
        // iOS 9.0 and below - however you were previously handling it
        guard let modelURL = Bundle.main.url(forResource: "Test", withExtension:"momd") else {
            fatalError("Error loading model from bundle")
        }
        guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }
        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
        context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let docURL = urls[urls.endIndex-1]
        let storeURL = docURL.appendingPathComponent("Test.sqlite")
        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
        } catch {
            fatalError("Error migrating store: \(error)")
        }

    }
    // Do any additional setup after loading the view.
}

override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}


}

我要做的就是绑定应用程序的managedObjectContext,这是分配给已经存在的persistentContainer的暂存器,并绑定一个NSArrayController,以便我可以连接tableView和管理数据对象。同样,我对此并不陌生,所以请帮助我看看我在哪里犯错。谢谢。

0 个答案:

没有答案