iOS 创建一个在退出登录时可以销毁的单例

一、单例简介

单例模式是在软件开发中经常用的一种模式。单例模式通俗的理解是,在整个软件生命周期内,一个类只能有一个实例对象存在。

二、遇到的问题

在平时开发使用单例的过程中,有时候会有这样的需求,在用户登录成功时,将用户的信息记录在用户信息单例中,当用户退出登录后,因为这个用户单例的指针被静态存储器的静态变量引用着,导致用户单例不能释放,直到程序退出或者杀死后,内存才能被释放。那有没有一种方法能够在单例不需要的时候就释放掉,而不要等到App结束呢?下面就介绍一种可以销毁的单例。

三、代码

说的再多不如一句代码来的实在,直接上代码。

单例类如下所示:

SingletonTemplate.h文件

#import <Foundation/Foundation.h>

@interface SingletonTemplate : NSObject
/*!**生成单例***/
+ (instancetype)sharedSingletonTemplate;
/*!**销毁单例***/
+ (void)destroyInstance;
@end

SingletonTemplate.m文件

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));
}

 

四、代码介绍

关于代码.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:----释放了

 

转载于:https://www.cnblogs.com/zhou--fei/p/6476783.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值