Creation of a singleton tool class
1. Use a one-time code
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
< #code to be executed once#>
});
2. It is not possible to make a subclass a singleton by means of inheritance. If inherited, the following two questions are raised
-If the parent class is created first, then the object created by the subclass is always the parent class
-If you create a subclass first, the object created by the parent class is always a subclass
3. Macro definition Extraction Single example:
Declaration of the method
Implementation of the method
Use the method to determine if arc
#if __has_feature (OBJC_ARC)
#else
#endif
Later, you can use Interfacesingleton to replace the later method declaration
#define Interfacesingleton (name) + (instancetype) share# #name
#if __has_feature (OBJC_ARC)
ARC
#define IMPLEMENTATIONSINGLETON (name) \
+ (instancetype) share# #name \
{ \
Name *instance = [[Self alloc] init]; \
return instance; \
} \
Static name *_instance = nil; \
+ (Instancetype) Allocwithzone: (struct _nszone *) zone \
{ \
Static dispatch_once_t Oncetoken; \
Dispatch_once (&oncetoken, ^{\
_instance = [[Super Allocwithzone:zone] init]; \
}); \
return _instance; \
} \
-(ID) Copywithzone: (Nszone *) zone{\
return _instance; \
} \
-(ID) Mutablecopywithzone: (nszone *) zone \
{ \
return _instance; \
}
#else
Mrc
#define IMPLEMENTATIONSINGLETON (name) \
+ (instancetype) share# #name \
{ \
Name *instance = [[Self alloc] init]; \
return instance; \
} \
Static name *_instance = nil; \
+ (Instancetype) Allocwithzone: (struct _nszone *) zone \
{ \
Static dispatch_once_t Oncetoken; \
Dispatch_once (&oncetoken, ^{\
_instance = [[Super Allocwithzone:zone] init]; \
}); \
return _instance; \
} \
-(ID) Copywithzone: (Nszone *) zone{\
return _instance; \
} \
-(ID) Mutablecopywithzone: (nszone *) zone \
{ \
return _instance; \
} \
-(oneway void) release \
{ \
} \
-(instancetype) retain \
{ \
return _instance; \
} \
-(Nsuinteger) retaincount \
{ \
return maxfloat; \
}
#endif
Later if you need to create a singleton tool class directly create a. h file, copy the above code into the. h file. Import this header file in the proxy class. directly in the. h file of the Singleton class, Interfacesingleton (name) passed in parameters and Implementationsingleton (name) in the. m file.
Single Case design mode