ios-Single case

Source: Internet
Author: User

1 StaticDemoobj *instance;2 3 /**4 1. Rewrite Allocwithzone and instantiate a static variable with dispatch_once5 2. Write a +sharedxxx to facilitate other class calls6  */7 8 //in iOS, the allocation of memory space for all objects will eventually call the Allocwithzone method9 //If you want to do a singleton, you need to override this methodTen //GCD provides a method that is designed to create a singleton One+ (ID) Allocwithzone: (struct_nszone *) Zone A { -     StaticDemoobj *instance; -     the     //dispatch_once is thread-safe, Oncetoken defaults to 0 -     Staticdispatch_once_t Oncetoken; -     //Dispatch_once Macros Ensure that the instructions in the block code are executed only once -Dispatch_once (&oncetoken, ^{ +         //in a multithreaded environment, it will only be executed once and instance will only be instantiated once -Instance =[Super Allocwithzone:zone]; +     }); A     at     returninstance; - } -  -+(instancetype) shareddemoobj - { -     //If two threads are instantiated at the same time, it is possible to create two instances to in //if (!instance) { - //        //Thread 1 0x0000a to //        //Thread 2 0x0000b + //instance = [[Self alloc] init]; - //    } the //    //the pointer returned by the first thread has been modified!  * //return instance; $     return[[Self alloc] init];Panax Notoginseng } -  the  + macro for a single case A  the //. h + #defineSingleton_interface (Class) + (Instancetype) shared# #class; -  $ //. M $ #defineSingleton_implementation (Class) - class*_instance; -  the+ (ID) Allocwithzone: (struct_nszone *) Zone - { Wuyi     Staticdispatch_once_t Oncetoken; theDispatch_once (&oncetoken, ^{  -_instance =[Super Allocwithzone:zone]; Wu     });  -  About     return_instance; $ }  -  -+ (Instancetype) shared##class  - {  A     if(_instance = =Nil) {  +_instance = [[classalloc] init];  the     }  -  $     return_instance; the}

ios-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.