Example of Swift single case

Source: Internet
Author: User

Sometimes, we need a class as long as the initialization is enough, such as the audio player this instance, so we need to use a single case, familiar with C + + and OC know how to write

Class Csingleton/* Lazy */{public:    Static Csingleton * getinstance ()    {               if (m_pinstance = NULL)//Determine if the first call to 
   m_pinstance = new Csingleton;        return m_pinstance;    }        void Relaseinstance ()        {            Delete this;        } Private:        Csingleton ()//constructor is private        {        }        Csingleton (const csingleton& that)//copy constructor should also be private        {                }        ~csingleton ()        {            m_pinstance = NULL;        }        Static Csingleton *m_pinstance;         };

+ (singalclass*) shareinstance//  Singleton use the + sign, the following can be written as a macro call {//using GCD to create a singleton mode//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. Static dispatch_once_t once;dispatch_once (&once, ^{single=[singalclass alloc];}); return single;}

The Swfit is simpler:

Class Swiftysingleton {static let shared = Swiftysingleton ()//"Lazy instantiation" global variable is automatically placed in dispatch_once block [4] private init () {}}

Example of Swift single case

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.