@SanMao
2015-08-07T09:56:18.000000Z
字数 1415
阅读 991
知识补充
一般情况下如果一个类是单例,那么都会提供一个类方法勇于快速创建单例对象,而且这个类方法的名称有一定的规律:
把以下代码放入一个.h文件中,包含这个文件就可以快速创建单例了
//
// Single.h
// 单例
//
// Created by 沈方武 on 15/8/7.
// Copyright © 2015年 沈方武. All rights reserved.
// 快速创建单例
#define interfaceSingle(name) + (instancetype)share##name
#if __has_feature(objc_arc)
// 如果是ARC
#define implementationSingle(name) + (instancetype)share##name \
{ \
return [[self alloc] init]; \
} \
static id _instance; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
}
#else
// 如果不是ARC
#define implementationSingle(name) + (instancetype)share##name \
{ \
return [[self alloc] init]; \
} \
static id _instance; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
}\
- (oneway void)release \
{} \
- (instancetype)retain \
{ \
return _instance; \
} \
- (NSUInteger)retainCount \
{ \
return MAXFLOAT; \
}
#endif