不熟悉单例的朋友,请先看Objective-C -- 单例设计模式
宏定义抽取单例,顾名思义,使用宏定义来替代单例的代码.这样我们以后写单例,有这个写好的单例代码的文件即可.
话不多少直接上代码.
这个文件保存的就是单例的代码,这里使用宏定义来替代这些代码
Singleton.h文件:
// 以后就可以使用interfaceSingleton来替代后面方法的声明
#define interfaceSingleton(name) +(instancetype)share##name
#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name) \
+ (instancetype)share##name \
{ \
name *instance = [[self alloc] init]; \
return instance; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone] init]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
}
#else
// MRC
#define implementationSingleton(name) \
+ (instancetype)share##name \
{ \
name *instance = [[self alloc] init]; \
return instance; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone] init]; \
}); \
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
Tools 文件
#import
#import "Singleton.h"
@interface Tools : NSObject
interfaceSingleton(Tools);
@end
@implementation Tools
implementationSingleton(Tools)
@end
Person 文件
#import
#import "Singleton.h"
@interface Person : NSObject
interfaceSingleton(Person);
@end
@implementation Person
implementationSingleton(Person);
@end
main文件
#import
#import "Tools.h"
#import "Person.h"
int main(int argc, const char * argv[]) {
Tools *t1 = [[Tools alloc] init]; //内部会调用 allocWithZone
Tools *t2 = [Tools new];// [[alloc] init] allocWithZone
Tools *t3 = [Tools shareTools];
Tools *t4 = [t3 copy];
Tools *t5 = [t3 mutableCopy];
NSLog(@"%p, %p, %p, %p, %p", t1, t2, t3, t4, t5);
Person *p1 = [Person sharePerson];
Person *p2 = [Person sharePerson];
NSLog(@"%p, %p", p1, p2);
// 如何判断当前是ARC还是MRC
// 可以在编译的时候判断当前是否是ARC
#if __has_feature(objc_arc)
NSLog(@"ARC");
#else
NSLog(@"MRC");
#endif
return 0;
}
输出结果:
2017-07-30 23:32:06.001955+0800 宏定义抽取单例[5759:221243] 0x100403420, 0x100403420, 0x100403420, 0x100403420, 0x100403420
2017-07-30 23:32:06.002197+0800 宏定义抽取单例[5759:221243] 0x100303bd0, 0x100303bd0
2017-07-30 23:32:06.002215+0800 宏定义抽取单例[5759:221243] ARC
我把项目调成MRC后的输出结果:
2017-07-30 23:32:57.144990+0800 宏定义抽取单例[5783:221591] 0x100200160, 0x100200160, 0x100200160, 0x100200160, 0x100200160
2017-07-30 23:32:57.145242+0800 宏定义抽取单例[5783:221591] 0x100500310, 0x100500310
2017-07-30 23:32:57.145266+0800 宏定义抽取单例[5783:221591] MRC
这样就大功告成了,以后我们写单例.只需要Singleton.h文件即可.对ARC 和 MRC 项目都管用!