Singleton mode in all object-oriented languages have oh involved, believe that as a programmer of you, will never be unfamiliar!
A singleton is an instance of static allocation that only opens up a piece of memory and does not re-open memory, saving memory!
The benefits of a single-column pattern are not explained here, but here are the full implementations of the single-column pattern:
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.
The following is an example of Surveyruntimedata:
static Surveyruntimedata *sharedobj = nil; First step: static instance, and initialize.
@implementation Surveyruntimedata
(surveyruntimedata*) sharedinstance//Second step: instance construction checks if the static instance is nil
{
@synchronized (self)
{
if (sharedobj = = nil) { [[Self alloc] init];}}
return sharedobj;
}
(ID) Allocwithzone: (Nszone *) zone//Third step: Overriding the Allocwithzone method
{
@synchronized (self) {
if (sharedobj = = nil) { sharedobj = [Super Allocwithzone:zone]; return sharedobj;}}
return nil;
}
(ID) Copywithzone: (Nszone *) zone//Fourth step
{
return self;
}
(ID) retain
{
return self;
}
(unsigned) Retaincount
{
return Uint_max;
}
(OneWay void) release
{
}
(ID) autorelease
{
return self;
}
(ID) Init
{
@synchronized (self) {
[Super init];//tend to put some variables to initialize. return self;
}
}
@end