您的位置:首页 > 移动开发 > Objective-C

Objective-C中的单例模式(工具类)

2016-01-02 18:24 573 查看
单例是iOS开发中经常会用到的一种设计模式,顾名思义,即创建一个类,该类在整个程序的生命周期中只有一个实例对象,无论是通过new,alloc init,copy等方法创建,或者创建多少个对象,自始至终在内存中只会开辟一块空间,直到程序结束,由系统释放.

如下图用不同的方式创建6个对象,但通过打印其内存地址,我们可以发现它们是共享同一块内存空间的.



由于在平时开发中经常用到,所以我将创建单例的方法定义成宏,并封装成一个工具类,提供了一个类方法来快速创建1个单例对象;

并且此类的单例包括了在MRC模式下的创建方式,保证了在MRC模式下,仍能使用该工具类来快速创建1个单例对象;

该工具类使用非常方便,只需在需要用到的类中导入头文件即可,以下是实现代码:

//
//  YYSharedModelTool.h
//  SharedModel
//
//  Created by Arvin on 15/12/21.
//  Copyright © 2015年 Arvin. All rights reserved.
//

#ifndef YYSharedModelTool_h
#define YYSharedModelTool_h

// .h 文件
// ##: 在宏中,表示拼接前后字符串
#define YYSharedModelTool_H(className) + (instancetype)shared##className;

#if __has_feature(objc_arc) // ARC 环境

// .m 文件
#define YYSharedModelTool_M(className)\
/****ARC 环境下实现单例的方法****/\
+ (instancetype)shared##className {\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(nullable NSZone *)zone {\
return self;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static id instance;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}

#else // MRC 环境

// .m 文件
#define YYSharedModelTool_M(className)\
\
+ (instancetype)shared##className {\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(nullable NSZone *)zone {\
return self;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static id instance;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}\
/****MRC 环境需要重写下面3个方法****/\
- (oneway void)release {\
\
}\
- (instancetype)retain {\
return self;\
}\
- (instancetype)autorelease {\
return self;\
}

#endif

#endif /* YYSharedModelTool_h */


END! 欢迎留言交流,一起学习...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: