標籤:http 使用 os io 檔案 資料 ar 問題
先別急,先簡單提一下單列的概念,當然具體的描述可能仁者見仁智者見智了!
1.單例設計模式(Singleton)
1> 什麼是單列: 它可以保證某個類建立出來的對象永遠只有1個
2> 作用(為什麼要用)
- 節省記憶體開銷
- 如果有一些資料, 整個程式中都用得上, 只需要使用同一份資源(保證大家訪問的資料是相同的,一致的)
- 一般來說, 工具類設計為單例模式比較合適
3> 怎麼實現,老程式員是碰到這樣的問題的!arc下就少了!
廢話少說,先來看一下我的單例模式下的標頭檔! 這裡主要是__has_feature(objc_arc) 判斷了一下是否為arc,所以代碼看上去有點多!
// 協助實現單例設計模式
// .h檔案的實現
define SingletonH(methodName) + (instancetype)shared##methodName;
// .m檔案的實現
if __has_feature(objc_arc) // 是ARC define SingletonM(methodName) \
static id _instace = nil; \
- (id)allocWithZone:(struct NSZone *)zone \
{ \
if (instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instace = [super allocWithZone:zone]; \
}); \
} \
return instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instace = [super init]; \
}); \
return instace; \
} \
\
- (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
- (id)copyWithZone:(struct NSZone *)zone \
{ \
return instace; \
} \
\
- (id)mutableCopyWithZone:(struct NSZone *)zone \
{ \
return instace; \
}
else // 不是ARC define SingletonM(methodName) \
static id _instace = nil; \
- (id)allocWithZone:(struct NSZone *)zone \
{ \
if (instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instace = [super allocWithZone:zone]; \
}); \
} \
return instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instace = [super init]; \
}); \
return instace; \
} \
\
- (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
\
- (oneway void)release \
{ \
\
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return 1; \
} \
- (id)copyWithZone:(struct NSZone *)zone \
{ \
return instace; \
} \
\
- (id)mutableCopyWithZone:(struct NSZone *)zone \
{ \
return instace; \
}
endif
這個裡面完完全全的做到了,單列所有情況的考慮,包括copy情況,多線程,還有自動判斷ARC和MRC情況!
用的時候只需要在包含標頭檔然後是用下面
.h檔案下:SingletonH(HttpTool)
.m檔案下:SingletonM(HttpTool)
這東西誰用誰知道!!!!嘻嘻!希望對讀者有協助!