Single case
The singleton pattern means that there is only one instance. The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole. This class is called a singleton class.
One is that a class can have only one instance, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the system itself.
Advantages of Singleton mode:
1. Instance control: Singleton prevents other objects from instantiating copies of their own Singleton objects, ensuring that all objects have access to unique instances.
2. Flexibility: Because classes control the instantiation process, classes can be more flexible in modifying the instantiation process
To implement a singleton class in objective-c, you need to do at least the following four steps:
1, for a singleton object to implement a static instance, and initialize, and then set to nil,
2. Implement an instance construction method to check if the static instance declared above is nil, and if it is new and returns an instance of this class,
3, rewrite the Allocwithzone method, to ensure that other people directly use Alloc and Init to try to gain a new strength when the time does not produce a new instance,
4, the appropriate implementation of Allocwithezone,copywithzone,release and Autorelease.
This is a multi-threaded lock that implements protection and does not allow a single instance to be created repeatedly
@synchronized (self) {
Singleton only needs to be created once to
if (singtoninstance = = nil) {
Singtoninstance = [[self class] alloc] init];
}
}
return singtoninstance;
}
Overwrite the method so that it does not produce a new object.
+ (ID) allocwithzone: (struct _nszone *) zone
{
if (singtoninstance = = nil) {
Singtoninstance = [Super Allocwithzone:zone];
}
return singtoninstance;
}
Don't let his reference count increase and produce new objects
-(ID) Copywithzone: (Nszone *) zone
{
return singtoninstance;
}
-(OneWay void) release
{
}
Don't let the app count decrease
-(ID) autorelease
{
return singtoninstance;
}
-(Nsuinteger) Retaincount
{
return Uint_max;
}
The role and use of iOS singleton