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

时间:2016-07-04 08:47:49

标签: 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]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,请告诉我哪里出错了,

2 个答案:

答案 0 :(得分:2)

使用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?

答案 1 :(得分:0)

尝试以下答案

  +(id)share
  {
     static ClassName *final=nil;
     if(final==nil)
     {
       final=[[self alloc]init];
     }
     return final;
   }