Interpretation and usage of single-case design pattern in IOS
One, the role of a single case
As the name implies, Singleton, that is, the object of this class can only be initialized once throughout the project. Its characteristics can be widely used in some resources that need to be shared globally, such as management classes, engine classes, and can be used to achieve the value of a single case. U IApplication, Nsuserdefaults, and so on are all system singleton cases in iOS.
Ii. The wording of a single case
There are two ways to use a single case:
Mode 1, regardless of thread
static Singlecase *manager = nil; + (Singlecase *) Defaultmanager {if (!manager) {singlecase = [[Self alloc] init]; Return manager; }}
mode 2, consider thread safety
+ (Singlecase *) Sharedmanager {static singlecase *managerinstance = nil; static dispatch_once_t predicate; Dispatch_once (&predicate, ^{managerinstance = [[Self alloc] init]; }); return managerinstance; }
Third, the optimization of the code
Through the above method, we can already use the class method to get this singleton, but many times, the project is very large, there may be many developers at the same time participate in the development of a project, for the convenience of security and Management code, but also for the creator is not the singleton but will use the singleton developer some tips, We will usually rewrite some methods:
First we implement a Alloc method ourselves:
+ (Instancetype) myalloc{return [Super Alloc];}
Make a few changes to our singleton implementation:
+ (Zyhpaymanager *) sharedmamager{static Zyhpaymanager * Manager; if (manager==nil) {Manager=[[zyhpaymanager myalloc]init]; } return manager;}
To override a method that instantiates some views of an object:
+ (Instancetype) alloc{nsassert (0, @ "This is a singleton object, please use the + (Zyhpaymanager *) Sharedmamager method"); return nil;} + (Instancetype) Allocwithzone: (struct _nszone *) zone{return [self alloc];} -(ID) copy{NSLog (@ "This is a singleton object, copy will not play any role"); return self;} + (Instancetype) new{return [self alloc];}
Note: The alloc here uses assertions to let any view of the program that creates objects through alloc break here, prompting the programmer. The Copy method simply returns the original object, does not do any processing, prints the information to the programmer to prompt.
An explanation of IOS singleton design pattern