Swift creates a singleton instance

Source: Internet
Author: User

Suppose a zlanimal class. I need to create TA when keeping a singleton

The practice in OC

    Static dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        _instance = [[Zlanimal alloc] init];    });


The approach in Swift is similar in that it creates a new class, Zlanimal class, that provides a quick way

Class Zlanimal:nsobject {    class var sharedmanager:zlanimal {        struct val{            static var oncetoken:dispatch_onc e_t = 0            static var staticinstance:zlanimal? = Nil        }        dispatch_once (&val.oncetoken, {()-Void in
   
    val.staticinstance = Zlanimal ()        })                return val.staticinstance!    }}
   


Controller call

        Let animal = Zlanimal.sharedmanager        println (animal) let                animal2 = Zlanimal.sharedmanager        println ( ANIMAL2)


Print the same address

<mySwift.ZLAnimal:0x7feebb508c60>

<mySwift.ZLAnimal:0x7feebb508c60>



It can also be more streamlined

Private Let sharedinstance = Zlanimal () class Zlanimal:nsobject {    class var sharedmanager:zlanimal {        return sha redinstance;}    }




Swift creates a singleton instance

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.