A:UIApplication 單例的三大特點(diǎn)
1礼殊、具有其他單例的特性屏镊,即內(nèi)存中只存在一個(gè)對(duì)象
2、程序一啟動(dòng)的時(shí)候就會(huì)創(chuàng)建
3剖煌、外界無(wú)法調(diào)用alloc方法刚夺,一旦調(diào)用系統(tǒng)就會(huì)拋出異常,使程序崩潰
B:實(shí)戰(zhàn)
1末捣、首先創(chuàng)建一個(gè)Test的類侠姑,在頭文件中聲明外部調(diào)用方法
@interface Test : NSObject
+ (instancetype)shareTest;
@end
2、然后在.m文件里面實(shí)現(xiàn)
a箩做、首先需要先聲明靜態(tài)變量
static Test *_instance = nil;
b莽红、重寫load方法
+ (void)load
{
//作用:加載類,會(huì)在每次程序啟動(dòng)的時(shí)候邦邦,會(huì)把所有的類加載進(jìn)內(nèi)存
_instance = [[self alloc] init];
}
C安吁、實(shí)現(xiàn)公開的方法
+(instancetype)shareTest{
return _instance;
}
d、最重要的是重寫alloc方法
+ (instancetype)alloc
{
//此時(shí)判斷是否已經(jīng)分配了內(nèi)存
if (_instance) {
// 如果已經(jīng)分配內(nèi)存燃辖,拋異常,告訴外界不運(yùn)用分配
NSException *excp = [NSException exceptionWithName:@"NSInternalInconsistencyException" reason:@"There can only be one Person instance." userInfo:nil];
[excp raise];
}
// 如果沒有分配內(nèi)存則調(diào)用父類方法開辟內(nèi)存
return [super alloc];
}