Sometimes it is because of the frequent creation of a singleton object and headache, one way to write many times? Of course you can use the OC language for encapsulation. However, the following describes a package in C language. As long as the following method is implemented, a singleton object will be built after two sentences.
1. Create a new. h file and implement the following methods in the file:
1/. h2 #defineSingleton_interface (Class) + (Instancetype) shared# #class;3 4 //. M5 #defineSingleton_implementation (Class)6 Static class*_instance;7 8+ (ID) Allocwithzone: (struct_nszone *) Zone9 { Ten Staticdispatch_once_t Oncetoken; OneDispatch_once (&oncetoken, ^{ A_instance =[Super Allocwithzone:zone]; - }); - the return_instance; - } - -+ (Instancetype) shared##class + { - if(_instance = =Nil) { +_instance = [[classalloc] init]; A } at - return_instance; -}
2. How to use.
Write the first sentence in the. h file in the class that you want to create the singleton in:
Singleton_interface (class name)
Write the second sentence in the. m file:
Well, after importing the header file in any project, and then implementing the two sentences in the class, you can easily use the singleton, and no longer have to write a lot of code frequently. Looks like it's not very big on!
IOS macros define a single case