0

我有一个 Objective C 项目,并试图从 Swift 视图控制器调用 AppDelegate。此代码不起作用:

let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext
4

3 回答 3

0

还有另一种方法。将“AppDelegate.h”包含在桥接头中,并确保解决任何错误。

然后创建一个 Objective C 对象,该对象具有一个返回应用程序委托对象的方法。它需要做的就是返回应用程序委托指针。目标文件还必须包含“AppDelegate.h”并解决任何错误。

-(yourAppDelegate*)giveMeTheAppDelegate{
 return yourAppDelegate;
}

然后在 Swift 文件中,您现在可以创建对象并引用任何方法。

let theObj = iAmAnObjectiveCObjectWithOneMethod()
let theDelegate = theObj.giveMeTheAppDelegate()
theDelegate?.thisMethodDisplaysText("hello")
于 2021-09-27T22:57:04.780 回答
0

您是否已将盐水头添加到您的项目中?

最重要的是,如果这样做,请确保将“AppDelegate.h”导入桥接头。

在 swift 类中,您应该可以使用以下方法调用它:

guard let appDele = UIApplication.sharedApplication().delegate as? AppDelegate else {
    fatalError("Unable to reference App Delegate, check settings and riding header")
}
let managedContext = appDele.managedObjectContext
于 2016-09-02T05:24:49.247 回答
0

.m文件中添加“ (ProjectName)-Swift.h ”

.h文件中添加@class AppDelegate

在 AppDelegate 文件中添加带有“ @objc ”扩展名的变量,以便可以在Objective C和 *** 文件中访问它。

于 2021-12-26T18:58:12.583 回答