将NSPersistentContainer传递给UIWindowSceneDelegate的正确方法是什么?

时间:2019-06-09 08:46:57

标签: swift uiapplicationdelegate uiapplication ios13 uiscenedelegate

现在,我正在通过UIApplication单例访问NSPersistentContainer以传递到主控制器,但是必须有一种更好的方法将数据从AppDelegate传递到SceneDelegate,在这种情况下为NSPersistentContainer。也许通过configurationForConnecting方法?

AppDelegate.swift

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

SceneDelegate.swift

导入UIKit

SceneDelegate类:UIResponder,UIWindowSceneDelegate,UISplitViewControllerDelegate {     var window:UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    let splitViewController = window?.rootViewController as! UISplitViewController
    let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
    navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
    splitViewController.delegate = self
    let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
    let controller = masterNavigationController.viewControllers.first as! MasterViewController

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let persistentContainer = appDelegate.persistentContainer
    controller.managedObjectContext = persistentContainer.viewContext
}

Info.plist

<dict>
    <key>UISceneClassName</key>
    <string>UIWindowScene</string>
    <key>UISceneDelegateClassName</key>
    <string>SceneTest.SceneDelegate</string>
    <key>UISceneConfigurationName</key>
    <string>Default</string>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UISceneStoryboardFile</key>
    <string>Main</string>
</dict>
</plist>

0 个答案:

没有答案