欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 单例模式的正确写法

程序员文章站 2022-07-14 07:52:35
...

大家平时写单例的时候可能没注意到,如果别人init了这个类,就会创建一个新的对象,要保证永远都只为单例对象分配一次内存空间,写法如下:

#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="">