單例標頭檔

來源:互聯網
上載者:User

標籤:style   blog   color   ar   檔案   sp   div   on   c   

 1 // 協助實現單例設計模式 2  3 // .h檔案的實現 4 #define SingletonH(methodName) + (instancetype)shared##methodName; 5  6 // .m檔案的實現 7 #if __has_feature(objc_arc) // 是ARC 8 #define SingletonM(methodName)  9 static id _instace = nil; 10 + (id)allocWithZone:(struct _NSZone *)zone 11 { 12 if (_instace == nil) { 13 static dispatch_once_t onceToken; 14 dispatch_once(&onceToken, ^{ 15 _instace = [super allocWithZone:zone]; 16 }); 17 } 18 return _instace; 19 } 20 21 - (id)init 22 { 23 static dispatch_once_t onceToken; 24 dispatch_once(&onceToken, ^{ 25 _instace = [super init]; 26 }); 27 return _instace; 28 } 29 30 + (instancetype)shared##methodName 31 { 32 return [[self alloc] init]; 33 } 34 + (id)copyWithZone:(struct _NSZone *)zone 35 { 36 return _instace; 37 } 38 39 + (id)mutableCopyWithZone:(struct _NSZone *)zone 40 { 41 return _instace; 42 }43 44 #else // 不是ARC45 46 #define SingletonM(methodName) 47 static id _instace = nil; 48 + (id)allocWithZone:(struct _NSZone *)zone 49 { 50 if (_instace == nil) { 51 static dispatch_once_t onceToken; 52 dispatch_once(&onceToken, ^{ 53 _instace = [super allocWithZone:zone]; 54 }); 55 } 56 return _instace; 57 } 58 59 - (id)init 60 { 61 static dispatch_once_t onceToken; 62 dispatch_once(&onceToken, ^{ 63 _instace = [super init]; 64 }); 65 return _instace; 66 } 67 68 + (instancetype)shared##methodName 69 { 70 return [[self alloc] init]; 71 } 72 73 - (oneway void)release 74 { 75 76 } 77 78 - (id)retain 79 { 80 return self; 81 } 82 83 - (NSUInteger)retainCount 84 { 85 return 1; 86 } 87 + (id)copyWithZone:(struct _NSZone *)zone 88 { 89     return _instace; 90 } 91  92 + (id)mutableCopyWithZone:(struct _NSZone *)zone 93 { 94     return _instace; 95 }96 97 #endif

 

單例標頭檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.