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

iOS单例写法

程序员文章站 2022-07-14 07:51:59
...

写法1:

实现文件:GCD

@implementation NewObject

static NewObject *_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 [NewObject shareInstance];
}

- (id)copyWithZone:(struct _NSZone *)zone {
   return [NewObject shareInstance];
}

- (id)mutableCopyWithZone:(struct _NSZone *)zone {
   return [NewObject shareInstance];
}

@end

写法2:

static A *_instance;

@implementation A

+ (instancetype)shared {
    
    @synchronized(self) {
        if (!_instance) {
            _instance = [[super allocWithZone: NULL] init];
        }
    }
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [A shared];
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [A shared];
}

- (id)mutableCopyWithZone:(struct _NSZone *)zone {
    return [A shared];
}

@end