iOS oc and Swfit create a singleton with Dispatch_once

Source: Internet
Author: User

Online already has the method, I here is to copy the next, the original link

http://bj007.blog.51cto.com/1701577/649413

Http://blog.csdn.net/u010124617/article/details/28856711?utm_source=tuicool

The dispatch_once_t here is an integral type for marking, nothing special.

The biggest benefit of using dispatch_once to achieve a single case is thread safety!! This is often asked by the interview that there is a thread-safety problem when creating a single case of database and network operations.

First look at OC.

+ (Accountmanager *) sharedmanager {     static accountmanager *sharedaccountmanagerinstance =  Nil;      static dispatch_once_t predicate; Dispatch_once (&predicate, ^{                 = [[Self alloc] init];     });     return sharedaccountmanagerinstance;}

Looking at Swfit, the internal struct is used because the static definition class attribute is not supported in Swift's class at this time.

class swiftsingleton{    class func shareinstance (),swiftsingleton{        struct  yrsingleton{            static0            static var Instance:swiftsingleton? = Nil        }        Dispatch_once (&yrsingleton.predicate,{                yrsingleton.instance=Swiftsingleton ()            }        )         return yrsingleton.instance!     }}

iOS oc and Swfit create 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.