Reputation: 1268
I'm using Appdelegate with some timers to do background checks. How can I trigger to do a check right now. I would have something like this in my Appdelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "test", userInfo: nil, repeats: true)
return true
}
func test() -> Bool {
print("true")
return true
}
is it admissable to do something like the following from any other class inside the app?
AppDelegate().test()
Upvotes: 3
Views: 201
Reputation: 81848
In model unit tests it's often nice not to have UIApplication
like framework classes, as they interfere with your tests in unforeseeable ways. But it's no problem at all to instantiate as many instances of your UIApplicationDelegate
as you want:
let sut = AppDelegate()
XCTAssertTrue(sut.test(), "test failed")
It's a delegate class and as such, does not interfere with UIKit by just instantiating.
Also in normal app code you could do the same without harming the rest of your app—it's just less common to do these kind of tests within the actual app target.
Upvotes: 1
Reputation: 16246
If you need access to some method or property of your app delegate, you could do something like this:
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
// Use your app delegate instance:
appDelegate.test()
}
Also, the code you wrote:
AppDelegate.test()
...is wrong; here test()
is an instance method, so it should be called on an instance (not the class - notice the capital initial).
Upvotes: 1
Reputation: 701
You can, but not by making another instance of AppDelegate but use the shared instance of it.
if let delegate = UIApplication.sharedApplication().delegate as? YOURAPPDELEGATE
Try above code.
Upvotes: 1