Basic concepts: The Singleton design mode is one of the more common and widely used and simple design modes. Its design principle is Always Returns an instance, that is, a class always has only one instance Basic Steps for creating a singleton Design Mode 1: declare a static instance of a singleton object and initialize it as nil 2: Create a class method and generate an instance of this class. If there is only nil of this class instance, instantiate it. 3: overwrite allocWithZone: method to ensure that new objects are not generated after the user directly allocates and initializes them. 4: implement the NSCopying protocol and overwrite the release, autorelease, retain, and retainCount methods to ensure the status of the Singleton. 5: In a multi-threaded environment, use the @ synchronized keyword to ensure that the static instance is correctly initialized. Basic implementation of a singleton: Instance, UserContext. h header file: # Import
@ Interface UserContext: NSObject
@ Property (nonatomic, copy) NSString * name; @ property (nonatomic, copy) NSString * email; // Singleton class method + (id) define usercontext; @ end
UserContext. m implementation file: # Import "UserContext. h "// single instance object static UserContext * sigletonInstance = nil; @ implementation UserContext // generate Single Instance Object + (id) incluusercontext {@ synchronized (self) {if (sigletonInstance = nil) {sigletonInstance = [[self class] alloc] init] ;}return sigletonInstance ;} // The following method ensures that only one instance object + (id) allocWithZone :( NSZone *) zone {if (sigletonInstance = nil) {sigletonInstance = [super allocWithZone: zone];} return sigletonInstance;}-(id) copyWithZone :( NSZone *) zone {return sigletonInstance;}-(id) retain {return sigletonInstance;}-(oneway void) release {}-(id) autorelease {return sigletonInstance;}-(NSUInteger) retainCount {return UINT_MAX;} @ end Main. m test code: #import
#import "UserContext.h"int main(int argc, const char * argv[]){ @autoreleasepool { UserContext *userContext1=[UserContext shareUserContext]; UserContext *userContext2=[UserContext shareUserContext]; UserContext *userContext3=[[UserContext alloc]init]; UserContext *userContext4=[userContext3 copy]; [userContext1 release]; [userContext1 release]; [userContext1 release]; [userContext1 release]; NSLog(@" "); } return 0;}
Run The memory address of the above four objects is the same, indicating that these four objects are the same object. In this way, the singleton can be implemented. |