Dispatch_once Creating a single case

Source: Internet
Author: User

Singleton is the most common design pattern used in development, regardless of how many objects are created, return the same instance, share a piece of memory. OC creates a singleton, basically defines a class method, creates an object in it, and then returns the object, the next time it is created, it is judged whether the object exists, if there is a direct return, no re-creation, of course, the object is saved in the global static zone. With the introduction of GCD, the code is much simplified, so you can use the void Dispatch_once (dispatch_once_t *predicate,dispatch_block_t block) function in GCD to help you create a singleton , easy to understand.

// #import @interface  + (ID) shareinstance; // + (ID) sharedmanager; @end

//#import "Person.h"//static person *per = nil; @implementation Person+ (ID) shareinstance{StaticPerson *per =Nil; Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{per=[[Person alloc] init];    }); returnper; }  /*+ (ID) sharedmanager{@synchronized (self) {if (per = = Nil) {per = [[Super Allocwithzone:null] in        It]; }} return per;  + (ID) Allocwithzone: (Nszone *) zone{return [[self sharedmanager] retain];}-(ID) Copywithzone: (Nszone *) zone{return Self;} -(ID) retain{return self;}-(Nsuinteger) retaincount{return Nsuintegermax;}-(OneWay void) release{//do nothin G}-(ID) autorelease{return self;}*/ @end

Pros: Thread-safe, without writing @synchronized, or nslock to ensure thread safety.

Disadvantage: If the user creates an object in the form of person *per = [[Person alloc] init], then the object created by the class method is not shared.

Dispatch_once Creating a 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.