Swift:将AppDelegate实例作为类func得到线程1:EXC_BAD_INSTRUCTION

时间:2015-07-30 06:32:16

标签: ios swift appdelegate

我希望从class func中的AppDelegate获取我的AppDelegate引用。为什么会抛出Thread 1: EXC_BAD_INSTRUCTION

class func getDelegate() -> AppDelegate {
    return UIApplication.sharedApplication().delegate as! AppDelegate
}

我还尝试将其移至另一个实用程序类和常规func,但同样崩溃。

我有没有办法AppDelegate作为class func访问而不必写

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

在每个班级?

2 个答案:

答案 0 :(得分:4)

声明类函数以将AppDelegate类中的appDelegate作为

class func getDelegate() -> AppDelegate {
    return UIApplication.sharedApplication().delegate as! AppDelegate
}

要在其他课程中访问和使用appDelegate,请致电

    let delegate = AppDelegate.getDelegate()

    delegate.printHello()

答案 1 :(得分:0)

创建一个类,如下所示[在新类文件中或在上一个类之外的现有类文件中。 无需将其放在AppDelete.swift文件]

class Delegate
{
   static var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
}

您可以在任何课程中将其用作Delegate.appDelegate