In JavaProgramIs the singleton mode, which can be used in objective-C, but it is a little different from Java.
Let's take a look at how to define a singleton mode in Java.
Public classSingletonclass{
Private StaticSingletonclassInstance = NULL;
PrivateSingletonclass(){
}
Public static final getinstance (){
Synchorinzed (this ){
If (instance = NULL ){
Instance = newSingletonclass();
}
Return instance
}
}
}
There is a difference in iOS development. In objective-C, all objects can be passed through [SingletonclassAlloc] For memory allocation. In this way, a new instance object can be returned, and the alloc method is public and does not allow classes to be called. Therefore, you must override the alloc method.
Generally, the alloc method is called + (ID) allocwithzone :( zone *) for initialization. Therefore, you only need to judge the initialization status in allicwithzone.
Help
1234567891011 |
+ (ID) allocwithzone :( nszone *) Zone { If (instance = nil ){ Instance = [Super allocwithzone: Zone]; } Return instance; } |
In objective-C, the alloc method is used to allocate memory addresses to class instances. In short, it is used to initialize the memory addresses of instance members, this address is calculated based on the initial address + offset address. In fact, this process also exists in Java, except that when Java is in a static language and compiled into a clas file, all instance attributes in the class are recorded in a variable table, generally, the variable table is indirectly associated with the corresponding actual address. The objective-C is calculated based on the offset between the class attribute and the base address.
This is easy to understand. For example, we have defined an int * P pointer. If we use P [5], the pointer P points to the address + 2*5 as the address of P [5.
In the alloc method, only the memory address is allocated to the instance variable and the retain count is increased by 1. At this time, for the pointer variable, the address points to the nil value, to initialize an object, the object is initialized through the method starting with init. In objective-C, Address Allocation and initialization are separated. The new keyword in Java includes the process of Address Allocation and initialization, similar to the constructor in Java. However, objective-C is open, and there is no private constructor in Java.