从 AppDelegate 更改另一个文件中的变量

Changing a Variable in Another File from AppDelegate

背景

我正在尝试从 AppDelegate.swift.

访问 ProjectsController.swift 中的变量 managedObjectContext

代码

ProjectsController.swift中:

var managedObjectContext: NSManagedObjectContext? = nil

var fetchedResultsController: NSFetchedResultsController<Project> {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }

    let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()

    // Set the batch size to a suitable number.
    fetchRequest.fetchBatchSize = 20

    // Edit the sort key as appropriate.
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: false)

    fetchRequest.sortDescriptors = [sortDescriptor]




    //The output is "nil"
    print(self.managedObjectContext as Any)

    //Couldn't unwrap optional value (self.managedContext!)
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")





    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
        try _fetchedResultsController!.performFetch()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
}

AppDelegate.swift中:

let projectsViewController = ProjectsViewController()

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


    //The output prints both of the print statements, so it has executed the change in variable.  The viewContext also outputs as it is supposed to.
    print(self.persistentContainer.viewContext)
    //Here is where the variable changes
    projectsViewController.managedObjectContext = self.persistentContainer.viewContext
    print(true)
    return true
}

问题

我只是想知道为什么,即使我从 AppDelegate.swift 更新了变量,ProjectsController.swift 也无法解包该值,因为它仍然是 nil。连接是否有问题,或者是否有更好的方法从 AppDelegate.swift.

访问不同文件中的变量

额外信息:

关闭

我想不出任何其他信息可以提供,我是 Swift 的初学者,所以如果您需要额外的信息来解决这个问题,或者无法解决,请告诉我解决了。​​

感谢您的宝贵时间和帮助!

如果您在设置 managedObjectContext 之前使用 fetchedResultsController,就会发生这种情况。例如如果视图控制器尝试在加载数据后立即获取数据,并且在您有机会 运行 应用程序委托中设置 managedObjectContext 的代码之前。

建议您尝试将 ProjectsViewController 的创建与其依赖项保持在一起,这样它就永远不会处于无法使用的状态。例如,在您的应用委托中:

let projectsViewController: ProjectsViewController = {
    let vc = ProjectsViewController()
    vc.managedObjectContext = self.persistentContainer.viewContext
    return vc
}()

此代码将 projectsViewController 声明为立即执行的闭包(实际上是一个函数)的值。