单例的销毁

单例设计模式是iOS开发中一种非常常用的设计模式,大家也都很熟悉了。这里要说的是单例的销毁。由于某些需求,比如某个单例保存了用户信息,退出登录以后要清空用户信息,所以需要销毁这个单例。
代码如下:

#import 

@interface DXTest : NSObject

+ (DXTest *)sharedInstance;
+ (void)attempDealloc;

@end
#import "DXTest.h"

static dispatch_once_t once;
static id instance;

@implementation DXTest

+ (id)sharedInstance 
{
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}
- (void)dealloc
{
    NSLog(@"DXTest--释放了");
}
+ (void)attempDealloc
{
    once = 0; // 只有置成0,GCD才会认为它从未执行过.它默认为0.这样才能保证下次再次调用shareInstance的时候,再次创建对象.
    instance = nil;
}

@end

有人担心销毁后不能重新创建。但是经过本人实测,调用销毁方法后,再调用sharedInstance也是可以重新创建的。所以不用担心这个。
(单例的创建准确来说其实还要重写其他几个方法,这里重点是销毁,所以就把那几个方法省略了。)

你可能感兴趣的:(单例的销毁)