The Nomad
The Nomad

Reputation: 7425

Swift: getting AppDelegate instance as a class func results in Thread 1: EXC_BAD_INSTRUCTION

I want to get my AppDelegate reference from a class func in my AppDelegate. Why is this throwing a Thread 1: EXC_BAD_INSTRUCTION?

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

I have also tried to move this to another utility class and as a regular func, but getting the same crash.

Is there a way I can access the AppDelegate as a class func instead of having to write

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

in every class?

Upvotes: 2

Views: 6403

Answers (2)

iRiziya
iRiziya

Reputation: 3245

Create a class as shown below[in a new class file or in existing class file outside the previous class. No need to put it inside AppDelete.swift file]

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

and you can use it as Delegate.appDelegate in any class.

Upvotes: 0

fibnochi
fibnochi

Reputation: 1113

Declare class function to get appDelegate in AppDelegate class as

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

To access and use appDelegate in other class, call

    let delegate = AppDelegate.getDelegate()

    delegate.printHello()

Upvotes: 4

Related Questions