單例設計模式是iOS開發(fā)中一種非常常用的設計模式,大家也都很熟悉了庶骄。這里要說的是單例的銷毀驻呐。由于某些需求灌诅,比如某個單例保存了用戶信息,退出登錄以后要清空用戶信息含末,所以需要銷毀這個單例猜拾。
代碼如下:
#import <Foundation/Foundation.h>
@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才會認為它從未執(zhí)行過.它默認為0.這樣才能保證下次再次調(diào)用shareInstance的時候,再次創(chuàng)建對象.
instance = nil;
}
@end
有人擔心銷毀后不能重新創(chuàng)建。但是經(jīng)過本人實測佣盒,調(diào)用銷毀方法后挎袜,再調(diào)用sharedInstance也是可以重新創(chuàng)建的。所以不用擔心這個肥惭。
(單例的創(chuàng)建準確來說其實還要重寫其他幾個方法盯仪,這里重點是銷毀,所以就把那幾個方法省略了务豺。)