Just started to do iOS development, do not know how to create a single case, the search on the internet is mostly not too full, so summed up the two ways to create a single case
First declare the class method in the. h file
1 + (instancetype) sharedutils;
It is then implemented in the. m file, with two ways of implementing it
First, when you create an object, you first determine if you have created the object in the program.
1 Static Publicutils *defaultmanager = nil; 2 3 +(instancetype) sharedutils4{5 if (! Defaultmanager)6 defaultmanager = [[self allocwithzone:null] init]; 7 8 return Defaultmanager; 9 }
Second, the direct use of the system provides multithreading technology Dispatch_once
1+(instancetype) sharedutils2 {3 Staticpublicutils* _sharedutils =Nil;4 Staticdispatch_once_t _once;5Dispatch_once (&_once, ^{6_sharedutils =[[Self alloc] init];7 });8 9 return_sharedutils;Ten}
Dispatch_once (&_once, ^{});
This multi-threaded role to look at the name estimation is almost the same: for a task to execute and execute only once.
Welcome everyone to make suggestions and comments, we learn together, progress together.
Two ways to create a singleton in iOS