//
// Single.h
// 單例模式
//
// Created by lisilong on 15/8/18.
// Copyright © 2015年 longshao. All rights reserved.
//
// 判斷當前是否時ARC
// 注意點:
// 1.單例是不可以繼承的, 如果繼承引發問題
// * 如果先創建父類, 那麼永遠都是父類
// * 如果先創建子類, 那麼永遠都是子類
// 說明:
// 1.調用allocWithZone:方法,給對象分配內存空間;
// 2.retainCount方法返回-1,或無限大MAXFLOAT只是讓別的程序員一塊便知道你這是一個單利對象。
/** 類的聲明部分 */
#define SingleInterface(name) + (instancetype)share##name
/** 類的實現部分 */
#if __has_feature(objc_arc)
// ARC
#define SingleImplement(name) + (instancetype)share##name \
{ \
return [[self alloc] init]; \
} \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static id instance; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instance = [super allocWithZone:zone]; \
}); \
return instance; \
} \
- (nonnull id)copyWithZone:(nullable NSZone *)zone \
{ \
return self; \
} \
- (id)mutableCopyWithZone:(nullable NSZone *)zone \
{ \
return self; \
}
#else
// MRC
#define SingleImplement(name) + (instancetype)share##name \
{ \
return [[self alloc] init]; \
} \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static id instance; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instance = [super allocWithZone:zone]; \
}); \
return instance; \
} \
- (nonnull id)copyWithZone:(nullable NSZone *)zone \
{ \
return self; \
} \
- (id)mutableCopyWithZone:(nullable NSZone *)zone \
{ \
return self; \
} \
- (oneway void)release \
{} \
- (instancetype)retain \
{ \
return self; \
} \
-(NSUInteger)retainCount \
{ \
return MAXFLOAT; \
}
#endif