The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole.
Here the main introduction under ARC, the use of GCD to achieve a single case.
First step: Declare a static instance
Static Soundtool *_instance;
Step two: Overriding the initialization method
+ (ID) Allocwithzone: (struct _nszone *) zone
This method is called when the object is initialized to allocate memory, and when overridden, even if the user does not use the shared method to get the instance, its initialization can still guarantee that the same instance will be obtained.
After GCD, a convenient way to ensure that a code is executed only once is to provide a dispatch_once.
This code method does not need to be carefully memorized. The code snippet has been built into Xcode. When you knock down the dispath_once, you'll have smart hints.
Step three: Declare a class method to share an instance
+ (soundtool *) Sharedsoundtool
?
@implementation SoundTool
static SoundTool *_instance;
+ (SoundTool *)sharedSoundTool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance=[
self new
];
});
return _instance; }
+ (
id
)allocWithZone:(
struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance=[
super allocWithZone:zone];
});
return_instance; } @end
|