我正在开发我的第一个应用程序,并从AppDelegate注入ManagedObjectContext。
昨天我找到了一种新的方法,并创建了像here这样的独立CoreDataStack。
我的应用故事板是这样的:
My storyboard
有一个UITabBarController
,两个UINavigationControllers
。您可以看到哪个view controller's
使用CoreData。
问题:
Appdelegate的代码:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
coreDataStack = CoreDataStack(){
(response) -> Void in
self.completeAnySetup()
}
//Pass NSManagedObjectContext to many VCs in TabBarVC
let mainTabBarVC: UITabBarController = self.window!.rootViewController as! UITabBarController
if let navControllerOne = mainTabBarVC.viewControllers![0] as? UINavigationController {
let mainMenuVC = navControllerOne.viewControllers[0] as! MainMenuVC
mainMenuVC.coreDataStack = self.coreDataStack
}
return true }
然后从navControllerOne.viewControllers[0]
我将它注入下一个VC:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Segues.TrackedHistoryVC {
if let trackedHistoryVC = segue.destinationViewController as? TrackedHistoryVC {
trackedHistoryVC.hidesBottomBarWhenPushed = true
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
if let coreDataStack = coreDataStack {
trackedHistoryVC.coreDataStack = coreDataStack
}
}
}}
等等。但我认为这种方式更为复杂:let appDelegate = ..., let psc = ....
。
func fetchAndResult() { if let mainContext = mainContext { let fetchRequest = NSFetchRequest(entityName: "TrackedShipments") do { let results = try self.mainContext!.executeFetchRequest(fetchRequest) print(results) self.trackedShipments = results as! [TrackedShipments] } catch { print("Error") } } }
更新
我看了很多,找到了正确的方法并停下来:
private(set) var persistenceController: PersistenceController? = nil func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { persistenceController = PersistenceController(completion: { (result, failError) -> Void in print("Persistent controller is loaded") }) guard let mainTabBarVC: UITabBarController = self.window!.rootViewController as? UITabBarController else {fatalError()} guard let navControllerOne = mainTabBarVC.viewControllers![0] as? UINavigationController else { fatalError() } guard let navControllerTwo = mainTabBarVC.viewControllers![1] as? UINavigationController else { fatalError() } guard let mainMenuVC = navControllerOne.topViewController as? MainMenuVC else { fatalError() } guard let myCabinetVC = navControllerTwo.topViewController as? MyCabinetVC else { fatalError() } mainMenuVC.persistenceController = persistenceController myCabinetVC.persistenceController = persistenceController return true }
效果很好。因此,只有appdelegate可以设置持久性控制器(Core Data stack),而其他视图控制器只能读取它。
addPersistentStoreWithType
一个正确的store URL
。