我如何在swift中为iphone应用程序创建全局服务

cyb*_*eek 4 iphone service singleton ios swift

我是ios和swift的新手,并且真的不确定用于全球服务的方法.截至目前我的方法是 - 我创建一个NSTimer的对象,并以2分钟的固定时间间隔调用一个函数A().我需要在多种情况下调用它,如下所述:

  1. 当我启动我的应用程序时 - 那时我需要启动NSTimer并调用A().
  2. app的子页面之一有按钮名称"Show",当我点击相同的功能时应该调用.
  3. 当应用程序进入后台时,需要以2分钟的固定间隔调用相同的功能.

这是我的困惑 - 我需要只创建单个实例,以便不存在多个实例,并且如果在任何情况下它应该终止运行函数.

我只需要在swift中执行此操作.如果存在,请建议或提供任何示例.

谢谢

Shr*_*ada 6

我们假设,您的类为SomeService.以下是如何创建单例:

 class SomeService {


  static let sharedInstance : SomeService = {
    //Do any computations needed to have the args for SomeService initializer, if not you can omit this closure and directly assign SomeService() to sharedInstance
    return SomeService() //<--Call the designated initialiser to instantiate the object.
    }()

   //Other methods of the class....
}
Run Code Online (Sandbox Code Playgroud)

基本上,它只是一个类级别,让你的类的同一类型保持不变.希望这可以帮助.

您可以按如下方式访问单例:

SomeService.sharedInstance
Run Code Online (Sandbox Code Playgroud)