IOS Singleton Mode
In the afternoon, I helped my colleagues change the code for one afternoon. I was deeply stabbed and deeply felt the importance of the Code architecture. I felt that the design model should be well polished. As a result, let's look at the design pattern from easy to difficult. Let's start with the simplest Singleton pattern of iOS.
As the simplest design mode of iOS-singleton mode, the main function is to ensure that a class only has a unique instance in the project. Saves resources and reduces unnecessary expenses.
How to Create a Singleton?
Define a global variable:
static Singleton * _instance =nil;
Provides a class method interface for external calls:
+(instancetype)shareInstance{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance =[[super allocWithZone:NULL]init]; }); return _instance;}
Override System Call Method
When instantiating an object, we usually use the alloc, init, or copy method. When we call the alloc method, OC calls the allocWithZone method internally to apply for memory. The same principle applies to copying objects. The OC calls the copyWithZone method internally. Therefore, we need to rewrite these two methods to ensure the singularity of the instance:
+(instancetype)allocWithZone:(struct _NSZone *)zone{ return [Singleton shareInstance];}-(instancetype)copyWithZone:(struct _NSZone *)zone{ return [Singleton shareInstance];}
Let's call:
Singleton *obj1=[Singleton shareInstance]; NSLog(@"obj1=%@",obj1); Singleton *obj2=[Singleton shareInstance]; NSLog(@"obj2=%@",obj2); Singleton *obj3=[[Singleton alloc]init]; NSLog(@"obj3=%@",obj3); Singleton *obj4=[[Singleton alloc]init]; NSLog(@"obj4=%@",[obj4 copy]);
If the printed result address is the same, the result is as follows:
2016-03-04 18:26:00.204 obj1=
2016-03-04 18:26:00.205 obj2=
2016-03-04 18:26:00.205 obj3=
2016-03-04 18:26:00.205 obj4=