In a previous study note, an article was written about how to achieve a single example in OC: iOS learning note 4-objective C-Create a singleton since Apple introduced Grand Central Dispatch (GCD) (Mac OS 10.6 and iOS4.0), there is a new way to create a singleton, which is to use the Dispatch_once function, and of course there will be more and better ways to do it as the evolution progresses. Here's a brief introduction to how to create a singleton using Dispatch_once.
In development we will use Nsnotificationcenter, Nsfilemanager, etc. to get their instances through [Nsnotificationcenter defaultcenter] and [Nsfilemanager Defaultmanager] to get, in fact, this is a single case.
Let's look at the function first.
void Dispatch_once (dispatch_once_t *predicate, dispatch_block_t block);
The first parameter, predicate, is the predicate that checks whether the block of code represented by the second argument is called.
The second parameter is a block of code that will only be called once throughout the application. The code blocks in the Dispach_once function are only executed once and are thread-safe.
Next we will implement our own singleton, here is a Schoolmanager class, for this class to implement a single example
[CPP]View Plaincopy
- + (Schoolmanager *) sharedinstance
- {
- static Schoolmanager *sharedmanager;
- static dispatch_once_t Oncetoken;
- Dispatch_once (&oncetoken, ^{
- Sharedmanager = [[Schoolmanager alloc] init];
- });
- return Sharedmanager;
- }
So far, we have implemented a single case, everything is done, is not very simple!
Use the following method to obtain a unique instance:
[CPP]View Plaincopy
- Schoolmanager *schoolmanager = [Schoolmanager sharedinstance];
The above is a simple introduction of the use of dispatch_once function to achieve a single case, welcome to add and discuss!
IOS: Creating a singleton with Dispatch_once