六月丁香五月婷婷,丁香五月婷婷网,欧美激情网站,日本护士xxxx,禁止18岁天天操夜夜操,18岁禁止1000免费,国产福利无码一区色费

學(xué)習(xí)啦 > 知識大全 > 知識百科 > 百科知識 > ios什么是單例

ios什么是單例

時間: 歐東艷656 分享

ios什么是單例

單例模式是ios里面經(jīng)常使用的模式,例如

[UIApplicationsharedApplication] (獲取當前應(yīng)用程序?qū)ο?、[UIDevicecurrentDevice](獲取當前設(shè)備對象);

單例模式的寫法也很多。

第一種:

Java代碼#FormatImgID_0#
  1. static Singleton *singleton = nil;  
  2.   
  3. // 非線程安全,也是最簡單的實現(xiàn)  
  4. + (Singleton *)sharedInstance  
  5. {  
  6.     if (!singleton) {  
  7.         // 這里調(diào)用alloc方法會進入下面的allocWithZone方法  
  8.         singleton = [[self alloc] init];  
  9.     }  
  10.   
  11.     return singleton;  
  12. }  
  13.   
  14.   
  15. // 這里重寫allocWithZone主要防止[[Singleton alloc] init]這種方式調(diào)用多次會返回多個對象  
  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. // 加入線程安全,防止多線程情況下創(chuàng)建多個實例  
  2. + (Singleton *)sharedInstance  
  3. {  
  4.     @synchronized(self)  
  5.     {  
  6.         if (!singleton) {  
  7.             // 這里調(diào)用alloc方法會進入下面的allocWithZone方法  
  8.             singleton = [[self alloc] init];  
  9.         }  
  10.     }  
  11.   
  12.     return singleton;  
  13. }  
  14.   
  15.   
  16. // 這里重寫allocWithZone主要防止[[Singleton alloc] init]這種方式調(diào)用多次會返回多個對象  
  17. + (id)allocWithZone:(NSZone *)zone  
  18. {  
  19.     // 加入線程安全,防止多個線程創(chuàng)建多個實例  
  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.     /* 這段代碼無法使用, 那么我們?nèi)绾谓鉀Qalloc方式呢? 
  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