The singleton is that project is only initialized once, saving memory space. or share resources. For example, when creating a Bluetooth class, or to do WiFi communication is often used. can also be used to pass values.
Introduce two ways to create a single case
One, consider the wording of thread safety
/** * Consider thread-safe notation * * @return Modeltool object */+ (instancetype) sharemodel{ static Modeltool *model = nil; Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ model = [[Self alloc] init]; }); return model;}
Two, do not consider the thread-safe wording
/** * do not consider thread-safe notation * * @return Modeltool object */+ (instancetype) sharemodeltool{ static Modeltool *model = nil; if (!model) { model = [[Modeltool alloc] init]; } return model;}
Three, test these two kinds of wording
-(void) viewdidload { [super viewdidload]; 1.0 consider thread-safe modeltool *tool1 = [Modeltool Sharemodel]; Modeltool *tool2 = [Modeltool Sharemodel]; Modeltool *tool3 = [Modeltool Sharemodel]; NSLog (@ "tool1 = =%@ Tool2 = =%@ Tool3 =%@", tool1,tool2,tool3); 2.0 do not consider thread safety modeltool *t1 = [Modeltool sharemodeltool]; Modeltool *t2 = [Modeltool sharemodeltool]; Modeltool *t3 = [Modeltool sharemodeltool]; NSLog (@ "T1 = =%@ T2 = =%@ T3 =%@", t1,t2,t3);}
Four. Print results
2016-03-08 14:26:43.996 Single case design mode [2144:779656] tool1 = = <ModelTool:0x7fb3f1412d20> Tool2 = = <modeltool: 0x7fb3f1412d20> Tool3 = = <ModelTool:0x7fb3f1412d20> 2016-03-08 14:26:43.997 single case design mode [2144:779656] T1 = = <ModelTool:0x7fb3f15263d0> t2 = = <ModelTool:0x7fb3f15263d0> T3 = = <ModelTool:0x7fb3f15263d0>
Both methods guarantee that a piece of memory space is created.
Single-instance mode for IOS development