iOS开发--单例模式

前言:单例模式使用广泛,需要掌握.但是一个项目中往往存在许多单例,因此重复代码过多.使用类继承,是不可以的.因此写了一个宏包含在头文件中,方便复用.

如何自己写一个单例

0.创建一个类,继承NSObject

GXTool: NSObject() 

1.重写allocWithZone:方法,(alloc 方法会自动调用allocWithZone方法,所以不用重写)
使用一次性线程完成初始化.保证线程安全,或者使用互斥锁.

 //加互斥锁解决多线程访问安全问题
//    @synchronized(self) {
//        if (_instance == nil) {
//            _instance = [super allocWithZone:zone];
//        }
//    }
//本身线程安全
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

2.提供一个外部接口方法

+ (instancetype)sharedTool{
    return [[self alloc]init];
}

3.实现

-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

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

4.MRC下需要重写release,retain,retainCount方法

#if __has_feature(objc_arc)
//条件满足 ARC
#else
// MRC
-(oneway void)release{
}
-(instancetype)retain{
    return _instance;
}
//习惯
-(NSUInteger)retainCount{
    return MAXFLOAT;
}
#endif

福利:一个单例的宏,解决重复写单例,只用传递名称即可,适用ARC和MRC.

/* Singleton_h */
#ifndef Singleton_h
#define Singleton_h
#define SingletonH(name) +(instancetype) shared##name;
#if __has_feature(objc_arc)    //条件满足 ARC
#define SingletonM(name)static id _instance;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instance = [super allocWithZone:zone];\
    });\
    return _instance;\
}\
+ (instancetype)shared##name{\
    return [[self alloc]init];\
}\
- (nonnull id)copyWithZone:(nullable NSZone *)zone {\
    return  _instance;\
}\
- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {\
    return _instance;\
}\

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

#endif
/* Singleton_h */

你可能感兴趣的:(iOS开发--单例模式)