IOS Study Notes-use dispatch_once to create a singleton

Source: Internet
Author: User

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 is a SchoolManager class, which implements the singleton [cpp] + (SchoolManager *) sharedInstance {www.2cto.com static SchoolManager * sharedManager for this class; static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {sharedManager = [[SchoolManager alloc] init] ;}); return sharedManager ;}so far, we have implemented a singleton, everything is done, isn't it easy! Use the following method to obtain a unique instance: [cpp] SchoolManager * schoolManager = [SchoolManager sharedInstance]; The preceding describes how to use the dispatch_once function to implement a singleton, you are welcome to add and discuss it!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.