Swift:将managedObjectContext从AppDelegate传递到UINavigationController

时间:2018-05-28 10:17:29

标签: swift core-data uinavigationcontroller closures appdelegate

我在Project中有一个带有@escaping方法的iOS项目(AppDelegate),用于为此项目创建NSPersistentContainer。然后在didFinishLaunchingWithOptions方法中调用此方法,如下所示:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var persistentContainer: NSPersistentContainer!

    func createProjectContainer(completion: @escaping (NSPersistentContainer) -> ()) {
        let container = NSPersistentContainer(name: "Project")
        container.loadPersistentStores { (_, error) in
            guard error == nil else { fatalError("Failed to load store: \(error!)") }
            DispatchQueue.main.async { completion(container) }
        }

    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        createProjectContainer { container in
            self.persistentContainer = container
            let storyboard = self.window?.rootViewController?.storyboard
            guard let vc = storyboard?.instantiateViewController(withIdentifier: "NavigationController") as? NavigationController else {
                fatalError("Cannot instantiate root view controller")
            }
            vc.managedObjectContext = container.viewContext
            self.window?.rootViewController = vc
        }
        return true
    }
}

NavigationController类只是UINavigationController的子类,它嵌入了UIViewControllerChildViewController)并且有一个NSManagedObjectContext变量({{1} }),我想传递给第一个managedObjectContext

ChildViewController

现在class NavigationController: UINavigationController { var managedObjectContext: NSManagedObjectContext! override func viewDidLoad() { super.viewDidLoad() guard let vc = self.childViewControllers.first as? ChildViewController else { fatalError("") } vc.managedObjectContext = managedObjectContext print("NavigationController: viewDidLoad") print("managedObjectContext ---> \(managedObjectContext)") } } 似乎被调用了两次。在第一次通话时,print("NavigationController: viewDidLoad"),在第二次通话中已分配。应用程序加载这两次是否重要?

由于关闭的managedObjectContext = nil属性,storyboard?.instantiateViewController(withIdentifier: "NavigationController")第一次加载NavigationController后,@escaping被称为之后的似乎正在发生。但是,如果我排除该行,只需获取对NavigationController的引用即可显示managedObjectContext

0 个答案:

没有答案