Ios 如何在obj c singleton类中限制对alloc、init的调用
我正在obj c中创建一个单例类,其中包含以下Dispatch once块 在Ios 如何在obj c singleton类中限制对alloc、init的调用,ios,objective-c,iphone,singleton,Ios,Objective C,Iphone,Singleton,我正在obj c中创建一个单例类,其中包含以下Dispatch once块 在ClassName.m中 + (instancetype)sharedInstance { static ClassName*objClassName = nil; static dispatch_once_t onceToken = 0; dispatch_once(&onceToken, ^{ objClassName = [[ClassName alloc]ini
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\u属性
取消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;
}
从这篇文章中试试下面的答案
+(id)share
{
static ClassName *final=nil;
if(final==nil)
{
final=[[self alloc]init];
}
return final;
}
此对象是NSObject的子类吗?@DannyBravo是的,如果要禁止alloc init和new,则必须使用
objClassName=[[super alloc]init]
。