Singleton design mode. This mode is often controversial, so I want to explain the singleton here.
In principle, Singleton is a class that is instantiated only once in the life cycle of a program. To ensure this, we use a static method of the class to generate and access objects.
Therefore, you access the singleton object of a class by using the method of benefit, rather than using alloc/init or static autorelease initialization method.
In many cases, we use a unique instance of a class. The most common is the main class of a program.
The following is a singleton function created with the name rootviewcontroller:
Static rootviewcontroller * sharedrootcontroller = nil;
+ (Rootviewcontroller *) sharedcontroller {
@ Synchronized (Self ){
If (sharedrootcontroller = nil ){
Sharedrootcontroller = [[self alloc] init] autorelease];
}
}
Return singlecontroller;
}
+ (ID) allocwithzone :( nszone *) Zone {
@ Synchronized (Self ){
If (sharedrootcontroller = nil ){
Sharedrootcontroller = [Super allocwithzone: Zone];
Return sharedrootcontroller;
}
}
Return nil;
}
Code Description:
1. synchronized is mainly a multi-threaded program. This command can limit the code in {} to one thread for execution. If a thread is not finished, other threads have to wait if they need to be executed.
2. The online search code seems to have been not added to autorelease. I think it should be added. This is because it is troublesome to call a function without release. (I personally think that for programs on iOS, autorelease should be taken into account for the creation of function return values)
3. allocwithzone is overloaded because it reads information from the specified memory area to create an instance. Therefore, if you need a Singleton, you must disable the modification of the current Singleton. Therefore, Nil is returned.