//helps implement a single-case design pattern//implementation of the. h file#defineSingletonh (MethodName) + (instancetype) shared# #methodName;//implementation of the. m file#if__has_feature (OBJC_ARC)//It's Arc .#defineSingletonm (MethodName)Static ID_instace =Nil;+ (ID) Allocwithzone: (struct_nszone *) Zone {if(_instace = =Nil) { Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];}); } return_instace;} - (ID) init {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super init];}); return_instace;} +(instancetype) shared# #methodName {return[[Self alloc] init];} + (ID) Copywithzone: (struct_nszone *) Zone {return_instace;} + (ID) Mutablecopywithzone: (struct_nszone *) Zone {return_instace;}#else //not arc .#defineSingletonm (MethodName)Static ID_instace =Nil;+ (ID) Allocwithzone: (struct_nszone *) Zone {if(_instace = =Nil) { Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];}); } return_instace;} - (ID) init {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super init];}); return_instace;} +(instancetype) shared# #methodName {return[[Self alloc] init];} -(OneWayvoid) Release {}- (ID) Retain {returnSelf ;} -(Nsuinteger) retaincount {return 1; } + (ID) Copywithzone: (struct_nszone *) Zone {return_instace;} + (ID) Mutablecopywithzone: (struct_nszone *) Zone {return_instace;}#endif
Put the above code into the. h header File
How to use: Implement Singletonh (Mothodname) (MethodName as method name) in a single file,. h
Singletonm implemented in. m (mothodname)
Single-Instance header files for iOS development