A singleton instance refers to an instance with static allocation, and all instances in the iphone sdk, such
[UIApplication sharedApplication] returns a pointer to a singleton object that represents the application. [UIDevice currentDevice] obtains an object that represents all hardware platforms.
By combining the class method with the Singleton, you can access the static instance anywhere in the program without using a pointer to the object or saving its instance variables. Function example for creating a unique instance (Common Singleton) of a class:
// 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 sharedRootController;
}
+ (Id) allocWithZone :( NSZone *) zone
{
@ Synchronized (self)
{
If (sharedRootController = nil)
{
SharedRootController = [super allocWithZone: zone];
Return sharedRootController;
}
}
Return nil;
}
-(Id) copyWithZone :( NSZone *) zone // Step 4
{
Return self;
}
-(Id) retain
{
Return self;
}
-(Unsigned) retainCount
{
Return UINT_MAX;
}
-(Oneway void) release
{
}
-(Id) autorelease
{
Return self;
}
-(Id) init
{
@ Synchronized (self ){
[Super init]; // usually put some variables to be initialized.
Return self;
}
}
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. It is troublesome if the called function does not have release (I think autorelease should be considered for programs on iOS used to create function return values ).
3. allocWithZone is overloaded because it reads information from the specified memory area to create an instance. Therefore, if the required Singleton already exists, you must disable the modification of the current Singleton, therefore, nil is returned.