美文网首页
iOS 单例

iOS 单例

作者: 青椒辣不辣 | 来源:发表于2020-12-11 10:13 被阅读0次

单例模式实现不能使用继承

定义单例实现 简写

+(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


相关文章

网友评论

      本文标题:iOS 单例

      本文链接:https://www.haomeiwen.com/subject/pnurgktx.html