大家平時(shí)寫單例的時(shí)候可能沒注意到,如果別人init了這個(gè)類,就會(huì)創(chuàng)建一個(gè)新的對(duì)象,要保證永遠(yuǎn)都只為單例對(duì)象分配一次內(nèi)存空間,寫法如下:
#import "Singleton.h"
@implementation Singleton
static Singleton* _instance = nil;
+(instancetype) shareInstance
{
static dispatch_once_t onceToken ;
dispatch_once(&onceToken, ^{
_instance = [[super allocWithZone:NULL] init] ;
}) ;
return _instance ;
}
+(id) allocWithZone:(struct _NSZone *)zone
{
return [Singleton shareInstance] ;
}
-(id) copyWithZone:(struct _NSZone *)zone
{
return [Singleton shareInstance] ;
}
@end
測試一下:
Singleton* obj1 = [Singleton shareInstance] ;
NSLog(@"obj1 = %@.", obj1) ;
Singleton* obj2 = [Singleton shareInstance] ;
NSLog(@"obj2 = %@.", obj2) ;
Singleton* obj3 = [[Singleton alloc] init] ;
NSLog(@"obj3 = %@.", obj3) ;
Singleton* obj4 = [[Singleton alloc] init] ;
NSLog(@"obj4 = %@.", [obj4 copy]) ;
可以發(fā)現(xiàn)打印的結(jié)果都是一樣的:
2014-12-15 16:11:24.734 ObjcSingleton[8979:303] obj1 = <singleton: 0x100108720="">
2014-12-15 16:11:24.735 ObjcSingleton[8979:303] obj2 = <singleton: 0x100108720="">
2014-12-15 16:11:24.736 ObjcSingleton[8979:303] obj3 = <singleton: 0x100108720="">
2014-12-15 16:11:24.736 ObjcSingleton[8979:303] obj4 = <singleton: 0x100108720="">