標籤:style blog io color ar os 使用 sp strong
網上關於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,因此需要重載
【原】ios下比較完美的單例模式,已驗證