单例的第一种方法
首先创建一个Danli的单例模式为例
@interface Danli:NSObject {
添加一类方法 (不是 实例方法)
static Danli *sharedCLDelegate = nil;
+(Danli *)sharedInstance{
@synchronized(self) {
if(sharedCLDelegate == nil) {
[[[self class] alloc] init]; // assignment not done here
}
}
return sharedCLDelegate;
}
}
在上面的代码中用到了关键字@synchronized是为了保证我们的单例的线程级别的安全,可以适用于多线程模式下。
我说重点把 用一下几种
对实例化的控制
- + (id)hiddenAlloc
- {
- return [super alloc];
- }
- + (id)alloc
- {
- NSLog(@"%@: use +sharedInstance instead of +alloc", [[self class] name]);
- return nil;
- }
- + (id)new
- {
- return [self alloc];
- }
- +(id)allocWithZone:(NSZone*)zone
- {
- return [self alloc];
- }
- - (id)copyWithZone:(NSZone *)zone
- { // -copy inherited from NSObject calls -copyWithZone:
- NSLog(@"MySingletonClass: attempt to -copy may be a bug.");
- [self retain];
- return self;
- }
- - (id)mutableCopyWithZone:(NSZone *)zone
- {
- // -mutableCopy inherited from NSObject calls -mutableCopyWithZone:
- return [self copyWithZone:zone];
- }
- +(id)sharedInstance修改如下:
- + (MySingletonClass *)sharedInstance {
- @synchronized(self) {
- if (sharedCLDelegate == nil) {
- [[[self class] hiddenAlloc] init]; // assignment not done here
- }
- }
- return sharedCLDelegate;
- }
单例的销毁
- + (void)attemptDealloc
- {
- if ([sharedCLDelegate retainCount] != 1)
- return;
- [sharedCLDelegate release];
- myInstance = nil;
- }
值得注意的是,上面这个attemptDealloc方法顾名思义,只是试图释放掉这个单例。如果retain的计数不为1,说明还有其他地方对该单例发送过retain消息。考虑到一个单例模式的生存周期是整个程序结束为止。所以,在程序的任何一个地方都没有必要向这个单例发送retain消息,即便是对这个单例有引用。而是调用sharedInstance方法来引用这个单例,这样做是安全的,也是合乎单例模式的技术含义的。