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

iOS 单例的标准写法

程序员文章站 2022-03-07 16:04:13
...

.h

#import <Foundation/Foundation.h>

@interface Singleton : NSObject

+ (instancetype)shareInstance;

@end

.m

#import "Singleton.h"

static Singleton *_instance = nil;

@implementation Singleton

+ (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

 

相关标签: 单例