The role of the singleton pattern: it can be guaranteed that there is only one instance of a class in a program, and that this instance is easy for the outside world to access. Always allocate memory only once to this class. Since the call to the Alloc method is called allocwithzonedispatch_once This method is guaranteed to be called only once and is automatically locked and thread safe.
Modification of works to non-arc in versions prior to 6.0
Xcode6.3 under Settings, modify the project under non-arc :
Define macros to implement the generality of the Singleton. You cannot use annotations when stitching macros. The last side cannot be added /.
//# #: Two # Number of connection strings and parameters#defineSingleton_h (name) + (instancetype) shared# #name;#defineSingleton_m (name)Static ID_instance;+ (ID) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone]; }); return_instance;} +(instancetype) shared# #name {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[[Self alloc] init]; }); return_instance;} -(OneWayvoid) Release {}- (ID) Autorelease {return_instance;} - (ID) Retain {return_instance;} -(Nsuinteger) retaincount {return 1; } + (ID) Copywithzone: (struct_nszone *) Zone {return_instance;}
Invocation Examples: |
-(ID) init { if (self = [super init]) { Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ Load Resources }); } return self; } Singleton_m (NetTool) Override the init method. The macro that invokes the singleton. How do I implement a single macro that is compatible with arc and non-arc? (add conditional compilation to judge) |
OC design mode--Singleton mode