Singleton on iOS (Obj-C实现单例模式)
参考地址:http://www.duckrowing.com/2010/05/21/using-the-singleton-pattern-in-objective-c/
static
MyGizmoClass
*
sharedGizmoManager
=
nil;
+ (MyGizmoClass * )sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone * )zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; // on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone * )zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; // denotes an object that cannot be released
}
- ( void )release
{
// do nothing
}
- (id)autorelease
{
return self;
}
+ (MyGizmoClass * )sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone * )zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; // on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone * )zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; // denotes an object that cannot be released
}
- ( void )release
{
// do nothing
}
- (id)autorelease
{
return self;
}