Custom Singleton for iOS development: custom for iOS development
Custom Singleton for iOS development
Here I use macros:
//. H
# Define single_interface (class) + (class *) shared # class;
//. M
// \ Indicates that the next row also belongs to a macro.
// ## It is a separator
- # Define single_implementation (class )\
- Static class * _ instance ;\
- \
- + (Class *) shared # class \
- {\
- If (_ instance = nil ){\
- _ Instance = [[self alloc] init]; \
- }\
- Return _ instance ;\
- }\
- \
- + (Id) allocWithZone :( NSZone *) zone \
- {\
- Static dispatch_once_t onceToken ;\
- Dispatch_once (& onceToken, ^ {\
- _ Instance = [super allocWithZone: zone]; \
- });\
- Return _ instance ;\
- }
Of course, there are other more comprehensive methods, but the principle of the above is the same, the practical use of the above can be used at ordinary times.
// The Singleton mode varies in the ARC \ MRC environment. You need to write two sets of different codes.
# If _ has_feature (objc_arc)
// ARC
// Override allocWithZone: method. Create a unique instance here (pay attention to thread security)
- + (Id) allocWithZone :( struct _ NSZone *) zone
- {
- @ Synchronized (self ){
- If (! _ Instance ){
- _ Instance = [super allocWithZone: zone];
- }
- }
- Return _ instance;
- }
- // Provides a class method to allow external access to a unique instance
- + (Instancetype) specified instance
- {
- @ Synchronized (self ){
- If (! _ Instance ){
- _ Instance = [[self alloc] init];
- }
- }
- Return _ instance;
- }
- // Implement copyWithZone: Method
- + (Id) copyWithZone :( struct _ NSZone *) zone
- {
- Return _ instance;
- }
# Else
// Non-ARC
// Non-ARC (MRC), single-instance mode implementation (several more steps than ARC)
// Override allocWithZone: method. Create a unique instance here (pay attention to thread security)
- + (Id) allocWithZone :( struct _ NSZone *) zone
- {@ Synchronized (self ){
- If (! _ Instance ){
- _ Instance = [super allocWithZone: zone];
- }
- }
- Return _ instance;
- }
- // Provides a class method to allow external access to a unique instance
- + (Instancetype) specified instance
- {
- @ Synchronized (self ){
- If (! _ Instance ){
- _ Instance = [[self alloc] init];
- }
- }
- Return _ instance;
- }
- // Implement copyWithZone: Method
- + (Id) copyWithZone :( struct _ NSZone *) zone
- {
- Return _ instance;
- }
- // Memory Management Method
- -(Id) retain
- {
- Return self;
- }
- -(NSUInteger) retainCount
- {
- Return 1;
- }
-
- -(Oneway void) release
- {
- }
-
- -(Id) autorelease
- {
- Return self;
- }
# Endif