我在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
的子类,它嵌入了UIViewController
(ChildViewController
)并且有一个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
。