学习啦 > 知识大全 > 知识百科 > 百科知识 > ios什么是单例

ios什么是单例

时间: 欧东艳656 分享

ios什么是单例

学习啦在线学习网 单例模式是ios里面经常使用的模式,例如

[UIApplicationsharedApplication] (获取当前应用程序对象)、[UIDevicecurrentDevice](获取当前设备对象);

学习啦在线学习网 单例模式的写法也很多。

第一种:

Java代码#FormatImgID_0#
  1. static Singleton *singleton = nil;  
  2.   
  3. // 非线程安全,也是最简单的实现  
  4. + (Singleton *)sharedInstance  
  5. {  
  6.     if (!singleton) {  
  7.         // 这里调用alloc方法会进入下面的allocWithZone方法  
  8.         singleton = [[self alloc] init];  
  9.     }  
  10.   
  11.     return singleton;  
  12. }  
  13.   
  14.   
  15. // 这里重写allocWithZone主要防止[[Singleton alloc] init]这种方式调用多次会返回多个对象  
  16. + (id)allocWithZone:(NSZone *)zone  
  17. {  
  18.     if (!singleton) {  
  19.         NSLog(@"进入allocWithZone方法了...");  
  20.         singleton = [super allocWithZone:zone];  
  21.         return singleton;  
  22.     }  
  23.   
  24.     return nil;  
  25. }  

 

 

 

第二种:

 

Java代码  #FormatImgID_1#
  1. // 加入线程安全,防止多线程情况下创建多个实例  
  2. + (Singleton *)sharedInstance  
  3. {  
  4.     @synchronized(self)  
  5.     {  
  6.         if (!singleton) {  
  7.             // 这里调用alloc方法会进入下面的allocWithZone方法  
  8.             singleton = [[self alloc] init];  
  9.         }  
  10.     }  
  11.   
  12.     return singleton;  
  13. }  
  14.   
  15.   
  16. // 这里重写allocWithZone主要防止[[Singleton alloc] init]这种方式调用多次会返回多个对象  
  17. + (id)allocWithZone:(NSZone *)zone  
  18. {  
  19.     // 加入线程安全,防止多个线程创建多个实例  
  20.     @synchronized(self)  
  21.     {  
  22.         if (!singleton) {  
  23.             NSLog(@"进入allocWithZone方法了...");  
  24.             singleton = [super allocWithZone:zone];  
  25.             return singleton;  
  26.         }  
  27.     }  
  28.       
  29.     return nil;  
  30. }  


 

第三种:

 

Java代码  #FormatImgID_2#
  1. __strong static Singleton *singleton = nil;  
  2.   
  3. // 这里使用的是ARC下的单例模式  
  4. + (Singleton *)sharedInstance  
  5. {  
  6.     // dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的  
  7.     static dispatch_once_t pred = 0;  
  8.     dispatch_once(&pred, ^{  
  9.         singleton = [[super allocWithZone:NULL] init];  
  10.     });  
  11.     return singleton;  
  12. }  
  13. // 这里  
  14. + (id)allocWithZone:(NSZone *)zone  
  15. {  
  16.       
  17.     /* 这段代码无法使用, 那么我们如何解决alloc方式呢? 
  18.      dispatch_once(&pred, ^{ 
  19.         singleton = [super allocWithZone:zone]; 
  20.         return singleton; 
  21.     }); 
  22.      */  
  23.     return [self sharedInstance];  
  24. }  
  25.   
  26. - (id)copyWithZone:(NSZone *)zone  
  27. {  
  28.     return self;  
  29. }  

245528