Swift Single case

Source: Internet
Author: User

There are several ways to implement a singleton, such as the following
Class Swiftsingleton {       class var Shared:swiftsingleton {       if! inner.instance {           inner.instance = Swiftsingleton ()           }           return inner.instance!       }              struct Inner {           static var Instance:swiftsingleton?       }   }   
The implementation of this code, the conditional judgment in GKFX, If inner.instance. Generates an instance for NULL, this code is simple to see that when the thread accesses the Swiftsingleton.shared method at the same time, the following problems arise, thread A determines that inner.instance is empty, switches to thread B immediately after entering the IF statement, and thread B Also Because thread a just enters the IF statement, this line of code
Inner.instance = Swiftsingleton ()  
Did not execute, at this time inner.instance is still empty, purebred B also made an if statement, in this case will create multiple instances, there is no guarantee that the uniqueness of the instance. 2, using GCD technology to achieve a single case mode
Class Swiftsingleton {       class var Shared:swiftsingleton {           dispatch_once (&inner.token) {               Inner.instance = Swiftsingleton ()           }           return inner.instance!       }       struct Inner {           static var Instance:swiftsingleton?           static var token:dispatch_once_t = 0       }          }   

Swift Single case

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.