In iOS, the memory allocation method for all objects calls Allocwithzone, such as the constructor alloc, so overriding this method allows you to implement a singleton.
Xcode is pre-written to implement the code quick instructions, knock Dispatch_once will see. This is a singleton code with GCD implementations.
The implementation code is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
+(
id
)allocWithZone:(
struct _NSZone *)zone {
static LYDemo * instance;
//是线程安全的,onceToKen默认是0
static dispatch_once_t onceToken;
//dispatch_once宏可以保证代码中的代码只会被执行一次。
dispatch_once(&onceToken, ^{
instance = [
super allocWithZone:zone];
});
return instance; } //上面代码只是保证了这个类只能有一个实例,而易读性略差,我们应该模仿系统的单例方式。 +(instancetype)sharedDemo {
return [[
self alloc]init]; }
|
To implement a single-case procedure:
1. Rewrite the Allocwithzone method and use GCD pre-written code block Dispatch_once snippet.
2. Create a method that starts with GKFX and mimics the system's singleton.