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, of course, as the evolution progresses, There will be more and better ways to appear. 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 take a look at the function void Dispatch_once (dispatch_once_t *predicate, dispatch_block_t block), where the first parameter predicate, This parameter is a predicate that checks whether the block of code represented by the second argument is called, and 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.
and then we're going to implement our own singleton, here is a Schoolmanager class that implements a singleton for this class
[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];
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS Basic Learning Log (vii) create a singleton with dispatch_once and use