Singleton mode : always returns the same instance of itself , which provides a global access point to the resources provided by the object of the class , and the returned instance can only be instantiated once.
There are two issues to be considered in designing a single design pattern:
(1): An object that initiates a call cannot instantiate a singleton object in another assignment, or it is possible to create multiple instances of a singleton class
(2): The restriction on instantiation of singleton objects should coexist with the reference counting memory model.
Singleton.h
#import <Foundation/Foundation.h>
@interface Singleton:nsobject
+ (Singleton *) sharedinstance;
@end
Singleton.m
#import "Singleton.h"
@implementation Singleton
Static Singleton *sharedsingleton = nil;
+ (Singleton *) sharedinstance{
if (sharedsingleton = =nil) {
//sharedsingleton = [[Singleton alloc] init];
//--------->>>>> (1)
//sharedsingleton = [[Super Allocwithzone:null] init];
/*
The reason for using Super instead of self is that self has overloaded the allocwithzone method
so the allocation of memory is realized by invoking the method of the parent class.
In fact , the Nsallocateobject method is called internally by the Allocwithzone method
*/
//--------->>>>> (2)
Sharedsingleton = [nsallocateobject([Self class], C7>0,NULL) init];
/*
the first number of parameters is type of Class
The second argument is the extra byte number of the instance variable used for the index , always 0
The third parameter is used to specify the area allocated in memory , which is generally NULL, which is represented as the default zone
Not available here (1) and using (2) The reason for this is that processing, whether instantiated Singleton or sub-class , all applicable
*/
}
returnSharedsingleton;
}
/*
call the class's allocwithzone incoming nszone to allocate space for the new object that is about to be generated
The purpose of overloading is to not produce new instances when using the object's alloc method
since The Alloc method actually calls the Allocwithzone:null method, it prevents other instances from being generated by Alloc
*/
+ (ID) Allocwithzone: (struct_nszone *) zone{
return [[self sharedinstance] retain];
}
/*
The purpose of overloading Copywithzone here is to prevent other instances from being generated when using the Copy method
*/
-(ID) Copywithzone: (nszone *) zone{
return self;
}
-(ID) retain{
return self;
}
-(nsuinteger) retaincount{
returnnsuintegermax;
}
-(void) release{
// do not do anything
}
-(ID) autorelease{
return self;
}
@end
Single-instance mode for iOS design mode