Reputation: 7425
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
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
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