Sometimes, we need a class as long as the initialization is enough, such as the audio player this instance, so we need to use a single case, familiar with C + + and OC know how to write
Class Csingleton/* Lazy */{public: Static Csingleton * getinstance () { if (m_pinstance = NULL)//Determine if the first call to
m_pinstance = new Csingleton; return m_pinstance; } void Relaseinstance () { Delete this; } Private: Csingleton ()//constructor is private { } Csingleton (const csingleton& that)//copy constructor should also be private { } ~csingleton () { m_pinstance = NULL; } Static Csingleton *m_pinstance; };
+ (singalclass*) shareinstance// Singleton use the + sign, the following can be written as a macro call {//using GCD to create a singleton mode//first parameter predicate, This parameter is a predicate that checks whether the block of code represented by the second argument is called, and the second parameter is a block of code that will only be called once throughout the application. The code blocks in the Dispach_once function are only executed once and are thread-safe. Static dispatch_once_t once;dispatch_once (&once, ^{single=[singalclass alloc];}); return single;}
The Swfit is simpler:
Class Swiftysingleton {static let shared = Swiftysingleton ()//"Lazy instantiation" global variable is automatically placed in dispatch_once block [4] private init () {}}
Example of Swift single case