iOS Basic Learning Log (vii) create a singleton with dispatch_once and use

Source: Internet
Author: User

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

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

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.