ios sharedInstance.

实现共享实例

oc :

  1. + (instancetype)sharedInstance {
  2. static id _sharedInstance = nil;
  3. static dispatch_once_t onceToken;
  4. dispatch_once(&onceToken, ^{
  5. _sharedInstance = [[self alloc] init];
  6. });
  7. return _sharedInstance;
  8. }

这段代码的模版在xcode右下角的模版里面有。

swift的共享实例:

  1. class Singleton {
  2. static let sharedInstance = Singleton()
  3. }

这种写法可以保证共享实例且线程安全。

如果要对这个共享实例进行初始化设置则采用

  1. class Singleton {
  2. static let sharedInstance: Singleton = {
  3. let instance = Singleton()
  4. // setup code
  5. return instance
  6. }()
  7. }

这种形式。

这个方法来自苹果的Documents文档😄

posted on 2017-01-17 01:14  码农时刻  阅读(1761)  评论(0编辑  收藏  举报