Objective-C中的單例模式(工具類),objective-c工具類
單例是iOS開發中經常會用到的一種設計模式,顧名思義,即建立一個類,該類在整個程式的生命週期中只有一個執行個體對象,無論是通過new,alloc init,copy等方法建立,或者建立多少個對象,自始至終在記憶體中只會開闢一塊空間,直到程式結束,由系統釋放.
如用不同方式建立了6個對象,但通過列印其記憶體位址,我們可以發現它們是共用同一塊記憶體空間的.
由於在平時開發中經常用到,所以我將建立單例的方法定義成宏,並封裝成一個工具類,提供了一個類方法快速建立1個單例對象;並且該工具類的單例包括了在MRC模式下的建立方式,保證了在MRC模式下,仍能使用該工具類來快速建立1個單例對象;該工具類使用非常方便,只需在需要用到的類中匯入標頭檔即可,以下是實現代碼:
1 // 2 // YYSharedModelTool.h 3 // SharedModel 4 // 5 // Created by Arvin on 15/12/21. 6 // Copyright © 2015年 Arvin. All rights reserved. 7 // 8 9 #ifndef YYSharedModelTool_h10 #define YYSharedModelTool_h11 12 // .h 檔案13 // ##: 在宏中,表示拼接前後字串14 #define YYSharedModelTool_H(className) + (instancetype)shared##className;15 16 #if __has_feature(objc_arc) // ARC 環境17 18 // .m 檔案19 #define YYSharedModelTool_M(className)\20 /****ARC 環境下實現單例的方法****/\21 + (instancetype)shared##className {\22 return [[self alloc] init];\23 }\24 \25 - (id)copyWithZone:(nullable NSZone *)zone {\26 return self;\27 }\28 \29 + (instancetype)allocWithZone:(struct _NSZone *)zone {\30 static id instance;\31 static dispatch_once_t onceToken;\32 dispatch_once(&onceToken, ^{\33 instance = [super allocWithZone:zone];\34 });\35 return instance;\36 }37 38 #else // MRC 環境39 40 // .m 檔案41 #define YYSharedModelTool_M(className)\42 \43 + (instancetype)shared##className {\44 return [[self alloc] init];\45 }\46 \47 - (id)copyWithZone:(nullable NSZone *)zone {\48 return self;\49 }\50 \51 + (instancetype)allocWithZone:(struct _NSZone *)zone {\52 static id instance;\53 static dispatch_once_t onceToken;\54 dispatch_once(&onceToken, ^{\55 instance = [super allocWithZone:zone];\56 });\57 return instance;\58 }\59 /****MRC 環境需要重寫下面3個方法****/\60 - (oneway void)release {\61 \62 }\63 - (instancetype)retain {\64 return self;\65 }\66 - (instancetype)autorelease {\67 return self;\68 }69 70 #endif71 72 #endif /* YYSharedModelTool_h */
END! 歡迎留言交流,一起學習...