1 , overview
single-case mode is a common software design pattern , which can ensure that a class has only one instance in the system and that the instance is easy to access, thus it is convenient to control the number of instances and save system resources.
If you want to have only one object for a class in the system, Singleton mode is the best solution, and the most common single case in iOS is uiapplication.
Application Scenarios:
Audio playback, background music!
Hardware resources: Accelerators, [UIScreen Mainscreen]
It is generally through sharedxx, mainxxx to obtain this singleton object.
Common interview questions: handwritten singleton
Advantages:
You can prevent other objects from instantiating a copy of a singleton object, ensuring that all objects have access to a unique instance
Disadvantages:
Once a singleton object is established, the object pointer is stored in the static area, and the memory space allocated by the Singleton object in the heap will not be released until the application terminates.
2 , single-instance implementation steps
First step: Rewrite Allocwithzone Method
The Allocwithzone method is a method that is eventually called when an object allocates memory space, overriding the method, guaranteeing that only one memory space is allocated
+ (ID)allocwithzone:(struct _nszone *) zone
{
Static Ticket *instance;
The static dispatch_once_t oncetoken;//is used to detect if it is only executed once
Dispatch_once is thread-safe and can be implemented in a multi-threaded environment where the code in the block is only executed once
Dispatch_once (&oncetoken, ^{
instance = [Super Allocwithzone:zone];
});
return instance;
}
Step Two: Establish sharedxxx class method for easy access to other classes
+ (Instancetype) sharedticket
{
return [[Self alloc] init];
}
Single-instance mode for iOS development