iOS Development singleton mode dispatch_once

Source: Internet
Author: User

What is a single case

Singleton mode is a kind of common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.

How to use single case in IOS development

Traditional single-instance construction method

+ (id)sharedInstance{    static id sharedInstance;    if(sharedInstance == nil){        sharedInstance = [[]self alloc] init]    }    return sharedInstance;}
The hidden trouble under multi-thread

In the case of multithreading, what happens if two threads call the Sharedinstance () method almost simultaneously? It is possible to create two instances of the class. In order to prevent this situation, we usually add locks.

+ (id)sharedInstance{    static id sharedInstance;    @synchronized(self)        if(sharedInstance == nil){            sharedInstance = [[]self alloc] init]        }               }    return sharedInstance;}
Dispatch_once

IOS 4.0 introduces GCD , **dispatchonce**, which is safe to work even in a multithreaded environment. Dispatchonce is used to ensure that the specified task is executed only once during the life cycle of the app. The following is a typical source code to initialize something. It can be elegant by using dispatch_once to create a single case.

+ (id)sharedInstance{    static dispatch_once_t once;    static id sharedInstance;    dispatch_once(&once, ^{        sharedInstance = [[self alloc] init];    });    return sharedInstance;}

iOS Development singleton mode 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.