如何从 Today View Widget 引用 AppDelegate?

How to reference the AppDelegate from a Today View Widget?

所以我有一个基于我的主应用程序构建的 Today View 小部件,我正在尝试访问一些存储的数据(通过 CoreData)。但是当我创建惰性变量来处理我的实体之一时,它无法编译。我理解它抛出的错误,但我不确定如何 handle/fix 它。

lazy var managedObjectContext : NSManagedObjectContext? = {
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    if let managedObjectContext = appDelegate.managedObjectContext {
        return managedObjectContext
    }
    else {
        return nil
    }
    }()

错误在第 2 行的 ..."as AppDelegate" 处抛出,它是一个 "Undeclared use of AppDelegate." 我想这是有道理的,因为 AppDelegate 在基本应用程序文件夹中,而不是在小部件的文件夹中.但是我不知道如何替换或修复它,以便代码能够编译和运行。有什么想法吗?

你不能。扩展是完全独立于您的主应用程序包的二进制文件,这是您的应用程序委托所在的位置。您将不得不创建一个共享库供您的主应用程序包和扩展程序使用,或者做大量的复制粘贴代码(首选前一种方法)。

来自developer guides

You can create an embedded framework to share code between your app extension and its containing app. For example, if you develop an image filter for use in your Photo Editing extension as well as in its containing app, put the filter’s code in a framework and embed the framework in both targets.

如果您不想,则不必创建正式的可链接库。只需确保您正在编写的库不引用不可用于扩展的 API。

Make sure your embedded framework does not contain APIs unavailable to app extensions, as described in Some APIs Are Unavailable to App Extensions. If you have a custom framework that does contain such APIs, you can safely link to it from your containing app but cannot share that code with the app’s contained extensions. The App Store rejects any app extension that links to such frameworks or that otherwise uses unavailable APIs.