我在AppDelegate之外创建了一个单独的CoreDataStack.swift对象,以便在使用CoreData时遵循此处的大部分建议。但是如何将MOC传递给AppDelegate中的rootViewController?我是否需要将代码添加到AppDelegate或ViewController?感谢任何可以在Swift帮助我的人,因为较旧的ObjC对我不起作用!
我的CoreDataStack包含MOC
lazy var managedObjectContext: NSManagedObjectContext = {
let managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) //
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext
}()
AppDelegate有一个创建一些数据的方法,在didFinishLaunchingWithOptions中我可以打印到控制台看它的工作
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let fetchRequest = NSFetchRequest(entityName: "WordList")
do {
let results = try coreDataStack.managedObjectContext.executeFetchRequest(fetchRequest)
if results.count == 0 {
addTestData()
}
} catch {
fatalError("Error fetching data!")
}
do {
if let results = try coreDataStack.managedObjectContext.executeFetchRequest(fetchRequest) as? [NSManagedObject] { //cast to an array of NSManagedObject
for result in results {
if let listName = result.valueForKey("listName") as? String {
print("Got a '\(listName)'")
}
}
}
} catch {
print("There was a fetch error")
}
// WHAT CODE HERE WILL PASS THE MOC TO THE ROOT VC?
return true
}
我在导航控制器中嵌入了一个简单的TableViewController
import UIKit
import CoreData
class WordListsTableViewController: UITableViewController {
var coreDataStack: CoreDataStack!
var wordLists = [WordList]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Word Lists"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "viewWordList")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// DO I NEED CODE HERE TO CALL THE MOC?
reloadData()
tableView.reloadData()
}
func reloadData() {
let fetchRequest = NSFetchRequest(entityName: "WordList")
do {
if let results = try coreDataStack.managedObjectContext.executeFetchRequest(fetchRequest) as? [WordList] {
wordLists = results
}
} catch {
fatalError("There was an error fetching wordLists!")
}
}
答案 0 :(得分:2)
有多种方法可以访问托管对象上下文。如果您在AppDelegate中定义了managedObjectContext
,则可以使用:
let appDelegate = UIApplicationDelegate.sharedApplication().delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
managedObjectContext.doStuff()
通过视图控制器传递managedObjectContext
的第二种方法是创建UIViewController
的扩展名。
extension UIViewController {
lazy var managedObjectContext: NSManagedObjectContext {
// Create core data stack or use singleton object
return coreDataStack.managedObjectContext
}
}
通过这样做,可以访问UIViewController
的每个子类上的managedObjectContext。然后你可以写:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.managedObjectContext.doSomething()
}
通过以上任何方式访问managedObjectContext,您可以在managedObjectContext
和您创建的任何rootViewController
中获得UIViewController
。