In a previous study note, I recorded an article on how to implement Singleton in OC: IOS study note 4-Objective C-create Singleton introduced grand from Apple
After Central Dispatch (GCD) (Mac OS 10.6 and ios4.0), a new method is available for creating a Singleton, that is, using the dispatch_once function. Of course, with the evolution, there will be more and better methods. Today, we will briefly introduce how to use dispatch_once to create a singleton.
During development, we will use nsicationicationcenter and nsfilemanager to obtain their instances through [nsicationicationcenter defacenter center] and [nsfilemanager defaultmanager]. In fact, this is a singleton.
Let's take a look at Void dispatch_once (dispatch_once_t * predicate, dispatch_block_t block). The first parameter is predicate, which is the predicate that checks whether the code block represented by the second parameter is called, the second parameter is the code block that will only be called once in the entire application. The code block in the dispach_once function is executed only once, and it is thread-safe.
Next we will implement our own singleton. Here we have a schoolmanager class to implement Singleton for this class.
+(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 Singleton, and everything is done. Isn't it easy!
You can obtain the unique instance as follows:
SchoolManager *schoolManager = [SchoolManager sharedInstance];
The above briefly introduces how to use the dispatch_once function to implement singleton. You are welcome to add and discuss it!
To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group
If the article is useful to you, click the forward button in the lower right corner to share it with more people!
At the same time, you are welcome to follow my Sina Weibo chat with me: @ Tang Ren _ Ryan