iOS单例宏

2017-05-24  本文已影响0人  yuandiLiao

开发中我们无可避免的使用到单例,单例的具体作用不多说了,这里记录一下单例宏的写法。新建一个header file,然后在里面具体实现代码如下。使用的时候在类的.h文件SingletonH(classname)传入类名和在.m文件中SingletonH(classname)传入类名即可

//@interface
#define SingletonH(classname)\
+ (classname *)shared##classname


//@implementation
#define SingletonM(classname) \
static classname* _instace = nil; \
+ (instancetype)shared##classname \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[super allocWithZone:NULL] init];\
}); \
} \
return _instace; \
} \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
return [self shared##classname];\
} \
\
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return [self shared##classname];\
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return [self shared##classname];\
}\
- (id)copyWithZone:(NSZone *)zone\
{ \
return [classname shared##classname];\
} \

单例类

#import <Foundation/Foundation.h>

@interface HFDataReportUMHandler : NSObject

SingletonH(HFDataReportUMHandler);

@end


#import "HFDataReportUMHandler.h"

@implementation HFDataReportUMHandler
SingletonM(HFDataReportUMHandler);

@end

//获取单例的对象
[HFDataReportUMHandler sharedHFDataReportUMHandler]

上一篇 下一篇

猜你喜欢

热点阅读