cyb*_*eek 4 iphone service singleton ios swift
我是ios和swift的新手,并且真的不确定用于全球服务的方法.截至目前我的方法是 - 我创建一个NSTimer的对象,并以2分钟的固定时间间隔调用一个函数A().我需要在多种情况下调用它,如下所述:
这是我的困惑 - 我需要只创建单个实例,以便不存在多个实例,并且如果在任何情况下它应该终止运行函数.
我只需要在swift中执行此操作.如果存在,请建议或提供任何示例.
谢谢
我们假设,您的类为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)
归档时间: |
|
查看次数: |
1786 次 |
最近记录: |