Singleton is the most common design pattern used in development, regardless of how many objects are created, return the same instance, share a piece of memory. OC creates a singleton, basically defines a class method, creates an object in it, and then returns the object, the next time it is created, it is judged whether the object exists, if there is a direct return, no re-creation, of course, the object is saved in the global static zone. With the introduction of GCD, the code is much simplified, so you can use the void Dispatch_once (dispatch_once_t *predicate,dispatch_block_t block) function in GCD to help you create a singleton , easy to understand.
// #import @interface + (ID) shareinstance; // + (ID) sharedmanager; @end
//#import "Person.h"//static person *per = nil; @implementation Person+ (ID) shareinstance{StaticPerson *per =Nil; Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{per=[[Person alloc] init]; }); returnper; } /*+ (ID) sharedmanager{@synchronized (self) {if (per = = Nil) {per = [[Super Allocwithzone:null] in It]; }} return per; + (ID) Allocwithzone: (Nszone *) zone{return [[self sharedmanager] retain];}-(ID) Copywithzone: (Nszone *) zone{return Self;} -(ID) retain{return self;}-(Nsuinteger) retaincount{return Nsuintegermax;}-(OneWay void) release{//do nothin G}-(ID) autorelease{return self;}*/ @end
Pros: Thread-safe, without writing @synchronized, or nslock to ensure thread safety.
Disadvantage: If the user creates an object in the form of person *per = [[Person alloc] init], then the object created by the class method is not shared.
Dispatch_once Creating a single case