问题描述
我有UIApplication的子类VC1
VC1
class CustomUIApplication: UIApplication {
override func sendEvent(_ event: UIEvent) {
super.sendEvent(event)
}
func stopTimer() {
}
func startTimer() {
}
}
VC2
class MyVC: ViewController {
// want to access start timer func here
}
CustomUIApplication的实例将位于main.swift中
UIApplicationMain(
CommandLine.argc,CommandLine.unsafeArgv,NSStringFromClass(CustomUIApplication.self),NSStringFromClass(AppDelegate.self)
)
任何帮助将不胜感激,谢谢。
解决方法
根据文档:
每个iOS应用程序都只有一个UIApplication实例(或者, 很少是UIApplication的子类)。启动应用程序后, 系统调用UIApplicationMain(::: :)函数;除其他外 任务,此函数创建一个Singleton UIApplication对象。 之后,您可以通过调用shared类方法来访问对象。
因此,在MyVC中,您应该可以执行CustomUIApplication.shared.startTimer()
。
说,我是否建议您考虑使用一个单独的类来处理开始/停止时间功能,而不是使用UIApplication的子类?您可以为此创建自己的单例,并以类似的方式从任何需要的地方访问它。
编辑:当然,您必须先定义static var shared: Self { UIApplication.shared as! Self }
。 (根据@Sulthan的评论)