OBJECTIVE-C Series-Single case

Source: Internet
Author: User

The earth has only one, so declare a Earth object on it, you can not declare two AH! Similarly, sometimes a class can have only one object case, such as a server, just want to save to a in//face, this way, the next time you can take out the last saved data.

// use global variables to implement singleton mode

a global variable is defined here , and then the global variable is returned in the Singleton method, which can also implement a singleton pattern

Earth * global=nil;

The global variable is returned in the Singleton method, but the object is created when the first call is made

+ (Earth *) Defaultearth

{

if (global==nil) {

global = [[Earth alloc]init];

}

return global;

}

****************************************

implementing a singleton pattern with static local variables

+ (Earth *) Defaultearth

{

static Earth* obj=nil;

if (obj==nil) {

obj=[[Earth alloc]init];

}

return obj;

}

**************************************

Using GCD to realize single case, super simple

-(Earth *) Shareearth

{

static Earth *sharedearthinstance = nil;

static dispatch_once_t oncetoken;

dispatch_once(&oncetoken, ^{

Sharedearthinstance = [[self alloc] init];

});

return sharedearthinstance;

}

OBJECTIVE-C Series-Single case

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.