1、单例简介spa
单例模式是在软件开发中常常用的一种模式。单例模式通俗的理解是,在整个软件生命周期内,一个类只能有一个实例对象存在。指针
2、遇到的问题code
在平时开发使用单例的过程当中,有时候会有这样的需求,在用户登陆成功时,将用户的信息记录在用户信息单例中,当用户退出登陆后,由于这个用户单例的指针被静态存储器的静态变量引用着,致使用户单例不能释放,直到程序退出或者杀死后,内存才能被释放。那有没有一种方法可以在单例不须要的时候就释放掉,而不要等到App结束呢?下面就介绍一种能够销毁的单例。对象
3、代码blog
说的再多不如一句代码来的实在,直接上代码。生命周期
单例类以下所示:内存
SingletonTemplate.h文件开发
#import <Foundation/Foundation.h> @interface SingletonTemplate : NSObject /*!**生成单例***/ + (instancetype)sharedSingletonTemplate; /*!**销毁单例***/ + (void)destroyInstance; @end
SingletonTemplate.m文件cmd
static SingletonTemplate *_instance=nil; @implementation SingletonTemplate + (instancetype)sharedSingletonTemplate { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance=[[self alloc] init]; NSLog(@"%@:----建立了",NSStringFromSelector(_cmd)); }); return _instance; } + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } + (void)destroyInstance { _instance=nil; } - (id)copyWithZone:(NSZone *)zone { return _instance; } - (void)dealloc { NSLog(@"%@:----释放了",NSStringFromSelector(_cmd)); }
4、代码介绍it
关于代码.h文件中有两个方法,一个是生成单例,另外一个是销毁单例;其中销毁单例方法,是将静态存储区的静态变量指针置为nil,这样单例对象在没有任何指针指向的状况下被系统回收了。
运行程序,打印的结果以下
- (void)viewDidLoad { [super viewDidLoad]; [SingletonTemplate sharedSingletonTemplate]; sleep(2); [SingletonTemplate destroyInstance]; } 打印结果: 2017-02-27 22:42:33.915 MyTestWorkProduct[3550:78078] sharedSingletonTemplate:----建立了 2017-02-27 22:42:35.990 MyTestWorkProduct[3550:78078] dealloc:----释放了