#import "SingalTon.h"
@implementation Singalton
Instance variables cannot be used in static methods
Need to be defined as a global variable or a static variable
Static Singalton * _singleton=nil;
+ (Singalton *) Sharesingleton
{
Before returning an object, it is necessary to determine whether the object was created before, and if it is not created, it is necessary to create an object that, if created , returns the last object created.
When multiple threads access the Singleton class at the same time, multiple singleton classes are created , and a lock is required ;
@synchronized(self)
{
if (_singleton = = nil)
{
_singleton=[[self alloc]init];
}
}
return _singleton;
}
You need to override the Alloc method to ensure that other users create and create only one object when using the Alloc method
+ (ID) alloc
//{
@synchronized (self)
// {
if (_singleton==nil)
// {
_singleton=[super Alloc];
// }
//
// }
return _singleton;
//}
The allocwithzone method is called inside the Alloc method
The Alloc method is not called when using the Allocwithzone method , so just rewrite it with Allocwithzone.
+ (ID) allocwithzone: (struct _nszone *) zone
{
@synchronized(self)
{
if (_singleton==nil)
{
_singleton=[Super Allocwithzone:zone];
}
}
return _singleton;
}
if in MRC ( Manual memory Management) , the object is a copy retain release autorelease these operations
/*-(ID) retain
{
return _singleton;
}
-(void) Release
{
}
-(ID) autorelease
{
return _singleton;
}
-(ID) copy
{
return _singleton;
}
-(Nsuinteger) Retaincount
{
return 1;
}*/
Initialization of Appdeledate directly with Alloc and invocation of the Singleton class method initialization will be the same address/object
Creating a singleton class