单例模式实现不能使用继承
定义单例实现 简写
+(instancetype)sharedInstance {
static RJRedPointView *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[RJRedPointView alloc] init];
});
return instance;
}
定义单例实现宏
///.h中写↓↓↓↓↓↓↓
#define SingleInstanceH(name) +(instancetype)share##name;
///.m中写↓↓↓↓↓↓↓
#if __has_feature(objc_arc)
///ARC
#define SingleInstanceM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+(instancetype)share##name\
{\
return [[self alloc]init];\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}
#else
//MRC
#define SingleInstanceM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+(instancetype)share##name\
{\
return [[self alloc]init];\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
-(oneway void)release\
{}\
\
-(instancetype)retain\
{\
return _instance;\
}\
\
-(NSUInteger)retainCount\
{\
return MAXFLOAT;\
}
#endif
#import <UIKit/UIKit.h>
#import "RJCustomToolConst.h"
NS_ASSUME_NONNULL_BEGIN
@interface RJRedPointView : UIView
SingleInstanceH(RJRedPointView);
@end
NS_ASSUME_NONNULL_END
#import "RJRedPointView.h"
@implementation RJRedPointView
SingleInstanceM(RJRedPointView);
@end












网友评论