Quick implementation of iOS Singleton
Singleton mode is a common design mode in iOS. The purpose of the singleton design mode is to make an object of this Class A unique instance in the system. Therefore, a unique method is required to create this object and return the address of this object. So when will we use the singleton mode? 1. A class can only have one instance and must be accessed from a well-known access point. 2. This unique instance can only be extended through subclass, and the extended object will not destroy the client code.
Depending on the Implementation of thread security, one is to use @ synchronized, and the other is to use the dispatch_once function of GCD.
To implement Singleton, you first need a static object pointing to the class itself, and then an initialization class function. Below are two types of implementation code.
1. @ synchronized
static InstanceClass *instance; + (InstanceClass *)defaultInstance{ @synchronized (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. Integration: if there are many Singleton instances in the project, you can use macro definition to implement singleton: (1) macro definition Singleton statement and implementation method (2) write method in the object to be used (3) Call
/*** Declaration ** @ param className class name ** @ return obtains the class Singleton */# define DEFINE_SINGLETON_FOR_HEADER (className) + (className *) shared # className; /*** implement Singleton ** @ param className class name ** @ return to obtain the singleton class */# define DEFINE_SINGLETON_FOR_CLASS (className) + (className *) shared # className {static className * shared # className = nil; static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {shared ## className = [[self alloc] init] ;}); return shared ## className ;}
Declare in ClockManager. h file
@ Interface ClockManager: NSObject/*** obtain the singleton Declaration */DEFINE_SINGLETON_FOR_HEADER (GMMobManager); @ end
Implemented in the ClockManager. m file
@implementation ClockManagerDEFINE_SINGLETON_FOR_CLASS(ClockManager);
@end
Call
[ClockManager sharedClockManager]