【问题标题】:How do you reference an Objective C AppDelegate from a Swift Class?如何从 Swift 类中引用 Objective C AppDelegate?
【发布时间】:2017-01-09 22:08:26
【问题描述】:

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

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

let managedContext = appDelegate.managedObjectContext

【问题讨论】:

  • 定义“不工作”。是否添加了桥接头?
  • 我添加了一个包含 #import "AppDelegate.h" 的引入标头,它消除了 AppDelegate 上的错误。现在我收到一个错误:let managedContext... Instance member 'appDelegate' cannot be used on type "ViewController" (The name is ViewController.swift) 感谢您的帮助。

标签: swift appdelegate mixed-code


【解决方案1】:

您是否已将 bring 标头添加到您的项目中?

最重要的是,如果这样做,请确保将“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

【讨论】:

  • "guard" 原因:一行上的连续声明必须用 ':' 分隔并且预期的声明错误 MSGS。添加一个;不能解决问题。感谢您的帮助
【解决方案2】:

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

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

-(yourAppDelegate*)giveMeTheAppDelegate{
 return yourAppDelegate;
}

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

let theObj = iAmAnObjectiveCObjectWithOneMethod()
let theDelegate = theObj.giveMeTheAppDelegate()
theDelegate?.thisMethodDisplaysText("hello")

【讨论】:

    【解决方案3】:

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

    .h文件中添加@class AppDelegate

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2020-10-28
      • 2017-10-15
      • 1970-01-01
      相关资源
      最近更新 更多