IOS-singleton (singleton) three ways of creation

Single case presentation

  • Singleton pattern: a class has only one instance object.
  • Use case: share a resource across the application (this resource only needs to be created once initialized).
  • ARC single example: provide a modified static static SingletonVC * _singletonVC global variables inside the class;; provide a convenient access method (instancetype) + share;; override the initWithZone method, guarantee will only single cases of distribution of a storage space.

Singleton writing

  • The first kind: the primary function of GCD (dispatch_once_t)
  • Recommendation Index:
#import "SingletonVC.h" / / create a static object to prevent external access to the static SingletonVC * _singletonVC; @implementation + SingletonVC (instancetype) allocWithZone: (struct * _NSZone) zone{static dispatch_once_t onceToken; / / a function dispatch_once (& onceToken, if ^{(_singletonVC = = Nil) {_singletonVC}} = [super allocWithZone:zone]; return _singletonVC;}); (instancetype) share{return + [[self alloc] init] @end;}
  • The second type: thread lock
  • Recommendation Index:
#import "SingletonVC.h" / / create a static object to prevent external access to the static SingletonVC * _singletonVC; @implementation + SingletonVC (instancetype) allocWithZone: (struct * _NSZone) zone{/ @synchronized lock (self) {if (_singletonVC = = Nil) {_singletonVC}} = [super allocWithZone:zone]; return _singletonVC;} + (instancetype) share{return [[self alloc] init] @end;}
  • The third type: lazy loading mode
  • Recommendation Index:
  • This method is not recommended and threads are unsafe.
#import "SingletonVC.h" static SingletonVC * _singletonVC; @implementation + SingletonVC (instancetype) allocWithZone: (struct * _NSZone) zone{if (_singletonVC = = Nil) {_singletonVC} = [super allocWithZone:zone]; return _singletonVC;} + (instancetype) share{return [[self alloc] init] @end;}