單例外部環(huán)境不可控,內(nèi)部可控。所有要保證單例唯一,就只有在其.m內(nèi)實現(xiàn)。
使用情景
高頻率去生產(chǎn)一個對象,然后又釋放。讓多個不相關(guān)的類共享數(shù)據(jù)。
創(chuàng)建單例
.h
//
// SafeSingleton.h
// OC基礎(chǔ)
//
// Created by FYJMac on 2018/5/2.
// Copyright ? 2018年 FYJMac. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SafeSingleton : NSObject
//創(chuàng)建或獲取單例對象
+ (instancetype)sharedSafeSingleton;
//注銷單例對象
- (void)cancelShare;
@end
.m
//
// SafeSingleton.m
// OC基礎(chǔ)
//
// Created by FYJMac on 2018/5/2.
// Copyright ? 2018年 FYJMac. All rights reserved.
//
#import "SafeSingleton.h"
@implementation SafeSingleton
static SafeSingleton *singleton;
//load是第一次加載該類時觸發(fā)(不管有沒有調(diào)用);initialize時第一次使用該類時觸發(fā)
+ (void)initialize
{
[SafeSingleton sharedSafeSingleton];
}
+ (instancetype)sharedSafeSingleton
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[SafeSingleton alloc] init];
});
return singleton;
}
//防止被創(chuàng)建多個
+ (instancetype)alloc
{
if (singleton) {
//拋出一個異常,通常是在寫框架的時候用到
NSException *exception = [NSException exceptionWithName:@"NSInternalInconsistencyException" reason:@"There can only be one Singleton indtance." userInfo:nil];
[exception raise];
}
return [super alloc];
}
- (void)cancelShare
{
singleton = nil;
}