gpt4 book ai didi

ios - 如何在obj c单例类中限制对alloc,init的调用

转载 作者:行者123 更新时间:2023-12-01 20:08:24 25 4
gpt4 key购买 nike

我正在obj c中使用以下Dispatch一次块创建一个单例类,

ClassName.m

+ (instancetype)sharedInstance
{
static ClassName*objClassName = nil;
static dispatch_once_t onceToken = 0;

dispatch_once(&onceToken, ^{
objClassName = [[ClassName alloc]init];
});

return objClassName;
}

我在 ClassName.h中使用以下代码,不允许使用alloc和init
- (id)init __attribute__((unavailable("You cannot init this class directly. Use sharedInstance to get the singleton Instance")));

+ (id)alloc __attribute__((unavailable("You cannot alloc this class directly. Use sharedInstance to get the singleton Instance")));

+ (id)new __attribute__((unavailable("You cannot use new this class directly. Use sharedInstance to get the singleton Instance")));

但是它不允许我的单例方法使用alloc init,请让我知道我要去哪里了,

最佳答案

使用UNAVAILABLE_ATTRIBUTE取消init方法,并实现initPrivate

+ (instancetype)shareInstance;

- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
implement

+ (instancetype)shareInstance {
static MyClass *shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[super allocWithZone:NULL] initPrivate];
});
return shareInstance;
}

- (instancetype)initPrivate {
self = [super init];
if (self) {

}
return self;
}

// MARK: Rewrite
+ (id)allocWithZone:(struct _NSZone *)zone {
return [MyClass shareInstance];
}

- (id)copyWithZone:(NSZone *)zone
{
return self;
}

从这篇文章 Singleton pattern in objc, how to keep init private?

关于ios - 如何在obj c单例类中限制对alloc,init的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38180369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com