iOS-单例模式-使用技巧 SingleModel-单例模式

单例可以保证在程序运行过程,一个类只有一个实例(一个对象)

一般将单例设置成宏,这样在使用的时候可以很方便。

我们可以按照下面的步骤实现单例

1、自定义一个.h文件,添加以下代码,这个文件就成了设置单例类的宏文件了。


#define HMSingletonH(name) + (instancetype)shared##name;


#if __has_feature(objc_arc)

    #define HMSingletonM(name) 
    static id _instace; 
 
    + (id)allocWithZone:(struct _NSZone *)zone 
    { 
        static dispatch_once_t onceToken; 
        dispatch_once(&onceToken, ^{ 
            _instace = [super allocWithZone:zone]; 
        }); 
        return _instace; 
    } 
 
    + (instancetype)shared##name 
    { 
        static dispatch_once_t onceToken; 
        dispatch_once(&onceToken, ^{ 
            _instace = [[self alloc] init]; 
        }); 
        return _instace; 
    } 
 
    - (id)copyWithZone:(NSZone *)zone 
    { 
        return _instace; 
    } 
    - (id)mutableCopyWithZone:(NSZone *)zone 
    { 
        return _instace; 
    }

#else

    #define HMSingletonM(name) 
    static id _instace; 
 
    + (id)allocWithZone:(struct _NSZone *)zone 
    { 
        static dispatch_once_t onceToken; 
        dispatch_once(&onceToken, ^{ 
            _instace = [super allocWithZone:zone]; 
        }); 
        return _instace; 
    } 
 
    + (instancetype)shared##name 
    { 
        static dispatch_once_t onceToken; 
        dispatch_once(&onceToken, ^{ 
            _instace = [[self alloc] init]; 
        }); 
        return _instace; 
    } 
 
    - (id)copyWithZone:(NSZone *)zone 
    { 
        return _instace; 
    } 
    - (id)mutableCopyWithZone:(NSZone *)zone 
    { 
        return _instace; 
    } 
 
    - (oneway void)release { } 
    - (id)retain { return self; } 
    - (NSUInteger)retainCount { return 1;} 
    - (id)autorelease { return self;}

#endif

2、要想使某一个类成为一个单例,只需要在这个的类的.h和.m
文件里面添加下面两句即可成为单例。

.h文件

HMSingletonH(类名)

.m文件

HMSingletonM(类名)

3、注意:

  • 单例不能被继承