Singleton mode is one of the common design patterns in iOS. The role of a singleton design pattern is to make an object of this class the only instance in the system, so it is necessary to create the object in a unique way and return the address of the object. So, when do we use singleton mode? 1. A class can have only one instance, and it must be accessed from a well-known access point. 2. This unique instance can only be extended by subclasses, and the extended object does not break the client code.
Depending on the implementation of thread safety, one is to use @synchronized , and the other is to use GCD's dispatch_once function.
To implement the Singleton, you first need a static object pointing to the class itself, followed by an initialization class function. Here are the two implementations of the code.
1. @synchronized
static instanceclass *instance; + (instanceclass *) defaultinstance{ @synchronized &N BSP; (self) { if (Instance == nil) { instance = [[InstanceClass alloc] init]; } } return instance;}
2, GCD
Static Instanceclass *instance; + (Instanceclass *) defaultinstance{static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{instance = [[Instanceclass alloc] init]; }); return instance;}
3 Synthesis: If you have more than one case in a project, you can use a macro definition to implement a single example: (1) macro definition of a single case Declaration and implementation method (2) in the object to be used in the Write method (3) Call
/** * declaration * * @param className class name * * @return obtain a singleton of this class */#define Define_singleton_for_header (ClassName) + (className *) shared# #className;/** * implementation of a single example * * @param className class name * * @return obtain a single case of this class */#define DEFINE_SINGLETON_FOR_CL ClassName + (ClassName *) shared# #className {static className *shared# #className = nil; static dispatch_once_t Onceto Ken Dispatch_once (&oncetoken, ^{shared# #className = [[Self alloc] init];}); return shared# #className; }
Declared in the ClockManager.h file
@interface clockmanager:nsobject/** * get a single case statement */define_singleton_for_header (Gmmobmanager); @end
Implemented in the CLOCKMANAGER.M file
@implementation Clockmanagerdefine_singleton_for_class (<span style= "Font-family:verdana, Sans-serif, song body;" >clockmanager</span><span style= "Font-family:verdana, Sans-serif, song body;" >);</span>
<span style= "Font-family:verdana, Sans-serif, song body;" > @end </span>
Call
[Clockmanager Sharedclockmanager]
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fast implementation of iOS single case