IOS: Creating a singleton with Dispatch_once

Source: Internet
Author: User

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
    1. + (Schoolmanager *) sharedinstance
    2. {
    3. static Schoolmanager *sharedmanager;
    4. static dispatch_once_t Oncetoken;
    5. Dispatch_once (&oncetoken, ^{
    6. Sharedmanager = [[Schoolmanager alloc] init];
    7. });
    8. return Sharedmanager;
    9. }

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
    1. 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

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.