大家平时写单例的时候可能没注意到,如果别人init了这个类,就会创建一个新的对象.
创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。当我们调用alloc方法时,OC内部会调用allocWithZone这个方法来申请内存,我们覆写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。拷贝对象也是同样的原理,覆写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象
要保证永远都只为单例对象分配一次内存空间,写法如下:
#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]) ;
结果:
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="">
网友评论