代码改变世界

Singleton Pattern in Objective-C

2010-10-27 19:58  Tracy E  阅读(499)  评论(0编辑  收藏  举报

Creating a Singleton Instance

 

A singleton object acts as a kind of control center, directing or coordinating the services of the class. Your class should generate a singleton instance rather than multiple instances when there is conceptually only one instance (as with, for example, NSWorkspace). You use singleton instances rather than factory methods or functions when it is conceivable that there might be multiple instances one day.

 

To create a singleton as the sole allowable instance of a class in the current process, you need to have an implementation similar to the code below. This code does the following:

Declare a static instance of your singleton object and initialize it to nil.

 

In your class factory method for the class (named something like “sharedInstance” or “getInstance”),

generate an instance of the class but only if the static instance is nil.

 

Override the allocWithZone: method to ensure that another instance is not allocated if someone tries to allocate and initialize an instance of your class directly instead of using the class factory method. Instead, just return the shared object.

 

Implement the base protocol methods copyWithZone:, release, retain, retainCount, and autorelease to do the appropriate things to ensure singleton status. (The last four of these methods apply to memory-managed code, not to garbage-collected code.)

 

 

Creating a Singleton Instance

 

//
//MySingletonClass.m
//Created by Tracy E on 10-10-27.
//Copyright 2010 tracy.cpp@gmail.com All rights reserved.
//
 
#import "MySingletonClass.h"
 
static MySingletonClass *singletonInstance = nil;
 
@implementation MySingletonClass
 
+ (id)getInstance {
     if (singletonInstance == nil)
     {
          singletonInstance = [[super allocWithZone:NULL] init];
     }
     returnsingletonInstance;
}
 
+ (id)allocWithZone:(NSZone *)zone
{
     return [[self getInstance] retain];
}
 
- (id)copyWithZone:(NSZone *)zone {
      returnself;
}
- (id)retain {
      returnself;
}
 
- (NSUInteger)retainCount {
       returnNSUIntegerMax; //denotes an object that cannot be released
}
 
- (void)release {
      //do nothing
}
 
- (id)autorelease {
      returnself;
}
 
@end