OC:单例的写法之 ARC 和 MRC

说明 时间
首次发布 2017年06月23日
最近更新 2019年09月03日

单例手写

// .h
#import 

NS_ASSUME_NONNULL_BEGIN

@interface MZDaoManager : NSObject

+ (instancetype)shareManager;

@end

NS_ASSUME_NONNULL_END


// .m
#import "MZDaoManager.h"

// 1、提供全局变量
static MZDaoManager *_manager = nil;
@implementation MZDaoManager

// 2、alloc/new -> allocWithZone
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}

// 3、提供类方法
+ (instancetype)shareManager {
    return [[self alloc] init];
}

// 4、严谨:兼容copy和mutableCopy
- (id)copyWithZone:(NSZone *)zone {
    return _manager;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _manager;
}

// 以下为兼容MRC,由于现在的工程绝大多数都是ARC,故可忽略。
#if !__has_feature(objc_arc)
- (NSUInteger)retainCount {
    return MAXFLOAT;
}

- (oneway void)release {}

- (instancetype)retain {
    return _manager;
}

#endif

@end

推荐:单例模式通用宏

#ifndef Single_h
#define Single_h

#define SingleH(name) + (instancetype)share##name;

#if __has_feature(objc_arc)
// ARC
#define SingleM(name)\
static id _manager = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _manager = [super allocWithZone:zone];\
    });\
    return _manager;\
}\
\
+ (instancetype)share##name {\
    return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
    return _manager;\
}\
\
- (id)mutableCopyWithZone:(NSZone *)zone {\
    return _manager;\
}

#else

// MRC
#define SingleM(name)\
static id _manager = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_manager = [super allocWithZone:zone];\
});\
return _manager;\
}\
\
+ (instancetype)share##name {\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _manager;\
}\
\
- (id)mutableCopyWithZone:(NSZone *)zone {\
return _manager;\
}\
\
- (NSUInteger)retainCount {\
    return MAXFLOAT;\
}\
\
- (oneway void)release {}\
\
- (instancetype)retain {\
    return _manager;\
}
#endif

#endif /* Single_h */
使用:
// .h
#import 

#import "Single.h"

NS_ASSUME_NONNULL_BEGIN

@interface MZDaoManager : NSObject

SingleH(DaoManager)

@end

NS_ASSUME_NONNULL_END


// .m
#import "MZDaoManager.h"

@implementation MZDaoManager

SingleM(DaoManager)

@end

你可能感兴趣的:(OC:单例的写法之 ARC 和 MRC)