1. 程式人生 > >iOS 建立單例

iOS 建立單例

#import "SingleInstance.h"

@interface SingleInstance ()<NSCopying,NSMutableCopying>

@end

//定義一個當前單例物件的一個例項,並賦值為nil
static SingleInstance *instance = nil;

@implementation SingleInstance
+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });

    return
instance; } /**************真正的單例需過載所有和建立有關的方法**************/ //alloc會觸發,防止通過alloc建立一個不同的例項 + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [super allocWithZone:zone]; }); return instance; } - (id)copyWithZone:(nullable NSZone *)zone { return
self; } - (id)mutableCopyWithZone:(nullable NSZone *)zone { return self; } /**************手動記憶體管理需做的操作**************/ - (instancetype)retain { return self; } - (oneway void)release { } - (instancetype)autorelease { return self; } - (NSUInteger)retainCount { return MAXFLOAT; } - (void
)dealloc { } @end