本文共 1181 字,大约阅读时间需要 3 分钟。
网上关于ios单例模式实现的帖子已经很多了,有很多版本,里面有对的也有不对的。我在使用过程中很难找到一个比较完美的方法,索性自己写一个吧,经过项目验证是比较合理的一个版本。
static PRAutoLoginView *s_sharedInstance = nil;+ (PRAutoLoginView *)shareInstance{ @synchronized(self) { if (s_sharedInstance == nil) { s_sharedInstance = [[[self class] hideAlloc] init]; } } return s_sharedInstance;}#pragma mark --#pragma mark singleton apis+ (id)hideAlloc{ return [super alloc];}+ (id)alloc//彻底屏蔽掉alloc函数{ NSAssert(1 == 0, @"[PRAutoLoginView]please use +shareInstance instead of alloc!"); return nil;}+ (id)new{ return [self alloc];}+ (id)allocWithZone:(struct _NSZone *)zone{ @synchronized(self) { if (s_sharedInstance == nil) { s_sharedInstance = [super allocWithZone:zone]; return s_sharedInstance; } } return nil;}- (id)copyWithZone:(NSZone *)zone{ NSAssert(1 == 0, @"[PRAutoLoginView]copy is not permitted!"); [self retain]; return self;}- (id)mutableCopyWithZone:(NSZone *)zone{ return [self copyWithZone:zone];}
这里要注意的一点时,allocWithZone时默认调用的,即使你没有显式地调用alloc或者allocWithZone,因此需要重载
本文转自编程小翁博客园博客,原文链接:http://www.cnblogs.com/wengzilin/p/4075996.html,如需转载请自行联系原作者