iOS 单例模式

来源:互联网 发布:node.js是js吗 编辑:程序博客网 时间:2024/06/16 18:20

单例模式的作用:

可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问
从而方便地控制了实例个数,并节约系统资源

单例模式的使用场合:
在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)

ARC中,单例模式的实现在.m中保留一个全局的static的实例static id _instance;重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)+ (instancetype)allocWithZone:(struct _NSZone *)zone{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instance = [super allocWithZone:zone];    });    return _instance;}提供1个类方法让外界访问唯一的实例+ (instancetype)sharedInstance{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instance = [[self alloc] init];    });    return _instance;}实现copyWithZone:方法- (id)copyWithZone:(struct _NSZone *)zone{    return _instance;}

单例宏:
Single.h

#define SingleH(name) +(instancetype)share##name;#if __has_feature(objc_arc)//条件满足 ARC#define SingleM(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 SingleM(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

如何使用单例宏:
新建一个类LLTool

#import <Foundation/Foundation.h>#import "Single.h"@interface Tool : NSObject<NSCopying, NSMutableCopying>SingleH(Tool)@end
#import "LLTool.h"@implementation XMGToolSingleM(Tool)@end