原文鏈接:https://my.oschina.net/zyboy/blog/617435
單例模式在iOS開發(fā)中是最為常用的模式之一,在應(yīng)用這個(gè)模式時(shí),單例對象的類必須保證只有一個(gè)實(shí)例存在。許多時(shí)候整個(gè)系統(tǒng)只需要擁有一個(gè)的全局對象,這樣有利于我們協(xié)調(diào)系統(tǒng)整體的行為。一般情況下,許多人都是按下面的方式寫單例模式:
#import "Singleton.h"
@implementation Singleton
static Singleton *shareSingleton = nil;
(instancetype)shareSingleton {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareSingleton = [[self alloc] init];
});
return shareSingleton;
}
@end
測試一下這種方法可行不:
Singleton *one = [Singleton shareSingleton];
NSLog(@"one = %@", one);
Singleton *two = [Singleton shareSingleton];
NSLog(@"two = %@", two);
Singleton *three = [[Singleton alloc] init];
NSLog(@"three = %@", three);
控制臺輸出內(nèi)容: 2015-12-22 15:31:38.230 Singleton[2264:1996979] one = <Singleton: 0x7fe598f4d3c0> 2015-12-22 15:31:38.230 Singleton[2264:1996979] two = <Singleton: 0x7fe598f4d3c0> 2015-12-22 15:31:38.231 Singleton[2264:1996979] three = <Singleton: 0x7fe598edc570>
由此可見,只有調(diào)用shareSingleton方法獲得的對象是相通的,用alloc init來構(gòu)造對象的時(shí)候,得到的確實(shí)不一樣的結(jié)果。究其原因,當(dāng)使用alloc init創(chuàng)建對象時(shí),在調(diào)用alloc方法時(shí),oc內(nèi)部會調(diào)用allocWithZone這個(gè)方法來申請內(nèi)存,為了避免allocWithZone申請新的內(nèi)存,可以重寫allocWithZone方法,在該方法中調(diào)用shareSingleton方法返回單例對象??截悓ο笠彩峭瑯拥牡览?。
完整代碼如下:
#import "Singleton.h"
@implementation Singleton
static Singleton *shareSingleton = nil;
(instancetype)shareSingleton {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareSingleton = [[super allocWithZone:NULL] init];
});
return shareSingleton;
}
(instancetype)allocWithZone:(struct _NSZone *)zone {
return [Singleton shareSingleton];
}
- (id)copyWithZone:(struct _NSZone *)zone {
return [Singleton shareSingleton];
}
@end
測試:
Singleton *one = [Singleton shareSingleton];
NSLog(@"one = %@", one);
Singleton *two = [Singleton shareSingleton];
NSLog(@"two = %@", two);
Singleton *three = [[Singleton alloc] init];
NSLog(@"three = %@", three);
Singleton *four = [[Singleton alloc] init];
NSLog(@"four = %@", [four copy]);
Singleton *five = [Singleton new];
NSLog(@"five = %@", five);
結(jié)果: 2015-12-22 17:01:52.350 Singleton[2399:2262945] one = <Singleton: 0x7f9e6be4ae30> 2015-12-22 17:01:52.350 Singleton[2399:2262945] two = <Singleton: 0x7f9e6be4ae30> 2015-12-22 17:01:52.351 Singleton[2399:2262945] three = <Singleton: 0x7f9e6be4ae30> 2015-12-22 17:01:52.351 Singleton[2399:2262945] four = <Singleton: 0x7f9e6be4ae30> 2015-12-22 17:01:52.351 Singleton[2399:2262945] five = <Singleton: 0x7f9e6be4ae30>
轉(zhuǎn)載于:https://my.oschina.net/zyboy/blog/617435
來源:https://www./content-4-445101.html
|