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
上一篇: 单例模式代码示例