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