I. The role of a single case
as the name suggests, a single example, that is, the object of this class can only be initialized once in the entire project. Its characteristics can be widely used in some resources that need to be shared globally, such as management class, engine class, and can be realized by single example. UIApplication, Nsuserdefaults, etc. are all systems in iOS as a single example.
Two ways of writing a single case pattern
1, commonly used writing
#import "LGManagerCenter.h"
static lgmanagercenter *managercenter;
@implementation lgmanagercenter
+ (Lgmanagercenter *) sharedmanager{
if (!managercenter)
managercenter= [[Self allocwithzone:null] init];
return managercenter;
}
@end
2, create a single instance class with GCD
#import "LGManagerCenter.h"
@implementation lgmanagercenter
+ (Lgmanagercenter *) sharedmanager{
static dispatch_once_t predicate;
Static Lgmanagercenter * Managercenter;
Dispatch_once (&predicate, ^{
managercenter=[[lgmanagercenter alloc] init];
return managercenter;
}
@end
Where the Dispatch_once function executes only once.
Third, the Code optimization
using the above method, we can already use the class method to get this single example, but many times, the project volume is very large, and there may be many developers to participate in the development of a project, in order to secure and manage the code convenience, Also, to give some hints to developers who are not the authors of this single example but who use this single example, we usually rewrite some of the methods:
First we implement a Alloc method ourselves:
+ (Instancetype) myalloc{return
[Super Allocwithzone:nil];
}
Make a few changes to our single implementation method:
+ (Zyhpaymanager *) sharedmamager{
Static Zyhpaymanager * Manager;
if (manager==nil) {
manager=[[zyhpaymanager myalloc]init];
}
return manager;
}
Overrides the method of instantiating some views of an object:
+ (instancetype) alloc{
nsassert (0, @ "This is a single Instance object, please use + (Zyhpaymanager *) Sharedmamager method");
return nil;
}
+ (Instancetype) Allocwithzone: (struct _nszone *) zone{return
[self alloc];
}
-(ID) copy{
NSLog (@ "This is a single instance object, copy will not play any role");
return self;
}
+ (Instancetype) new{return
[self alloc];
}
Note: The alloc here uses assertions so that any view of the program that creates the object through Alloc is broken here to give the programmer a hint. Copy method here simply returns the original object, does not do any processing, printing information to the programmer hint.