IOS 单例的两种方法

来源:互联网 发布:淘宝大v达人怎么申请 编辑:程序博客网 时间:2024/06/05 16:16

单例的第一种方法

首先创建一个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是为了保证我们的单例的线程级别的安全,可以适用于多线程模式下。

我说重点把  用一下几种

对实例化的控制

 

  1. + (id)hiddenAlloc  
  2. {  
  3.     return [super alloc];  
  4. }  
  5.   
  6.   
  7. + (id)alloc  
  8. {  
  9.     NSLog(@"%@: use +sharedInstance instead of +alloc", [[self class] name]);  
  10.     return nil;  
  11. }  
  12.   
  13.   
  14. + (id)new  
  15. {  
  16.     return [self alloc];  
  17. }  
  18.   
  19. +(id)allocWithZone:(NSZone*)zone  
  20. {  
  21.     return [self alloc];  
  22. }  
  23.   
  24. -   (id)copyWithZone:(NSZone *)zone  
  25. {   // -copy inherited from NSObject calls -copyWithZone:  
  26.     NSLog(@"MySingletonClass: attempt to -copy may be a bug.");  
  27.     [self retain];  
  28.     return self;  
  29. }  
  30.   
  31. - (id)mutableCopyWithZone:(NSZone *)zone  
  32. {  
  33.     // -mutableCopy inherited from NSObject calls -mutableCopyWithZone:  
  34.     return [self copyWithZone:zone];  
  35. }  
  36.   
  37. +(id)sharedInstance修改如下:  
  38.   
  39. + (MySingletonClass *)sharedInstance {  
  40.     @synchronized(self) {  
  41.         if (sharedCLDelegate == nil)   {  
  42.             [[[self class] hiddenAlloc] init]; // assignment not done here  
  43.         }  
  44.     }  
  45.     return sharedCLDelegate;  
  46. }  

 

单例的销毁

  1. + (void)attemptDealloc  
  2. {  
  3.     if ([sharedCLDelegate retainCount] != 1)  
  4.         return;  
  5.   
  6.     [sharedCLDelegate release];  
  7.     myInstance = nil;  
  8. }  

值得注意的是,上面这个attemptDealloc方法顾名思义,只是试图释放掉这个单例。如果retain的计数不为1,说明还有其他地方对该单例发送过retain消息。考虑到一个单例模式的生存周期是整个程序结束为止。所以,在程序的任何一个地方都没有必要向这个单例发送retain消息,即便是对这个单例有引用。而是调用sharedInstance方法来引用这个单例,这样做是安全的,也是合乎单例模式的技术含义的。

 

0 0