View code
@ InterfaceSingleton: nsobject
{
}
+ (Singleton *) sharedinstance;
-(Void) Operation;
@ End
View code
# Import " Singleton. h "
@ Implementation Singleton
Static Singleton * sharedsingleton _ = nil;
-( Void ) Operation
{
// Do something
Nslog ( @" Singleton " );
}
+ (Singleton *) sharedinstance
{
If (Sharedsingleton _ = nil)
{
Sharedsingleton _ = [nsallocateobject ([self Class ], 0 , Null) Init];
}
Return Sharedsingleton _;
}
+ ( ID ) Allocwithzone :( nszone *) Zone
{
Return [[Self sharedinstance] retain];
}
-( ID ) Copywithzone :( nszone *) Zone
{
Return Self;
}
-( ID ) Retain
{
Return Self;
}
-(Nsuinteger) retaincount
{
Return Nsuintegermax; // Denotes an object that cannot be released
}
-( Void ) Release
{
// Do nothing
}
-( ID ) Autorelease
{
Return Self;
}
@ End
==================================
View code
@ InterfaceMysingleton: Singleton
{
}
@ End
View code
@ ImplementationMysingleton
-(ID) Init
{
ReturnSelf;
}
-(Void) Operation
{
//Do something
Nslog (@"Mysingleton");
}
@ End
==================================
Client:
View code
Singleton * s = [mysingleton sharedinstance];
[S operation];