在单例上实现alloc

dan*_*anh 4 objective-c ios

我想在我的系统中有一个单例,但不是让调用者通过某种'sharedInstance'方法访问它,我希望他们能够不知道他们正在使用单例,换句话说,我我希望来电者能够说:

MyClass *dontKnowItsASingleton = [[MyClass alloc] init];
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,我尝试重写alloc如下:

// MyClass.m

static MyClass *_sharedInstance;

+ (id)alloc {

    if (!_sharedInstance) {
        _sharedInstance = [super alloc];
    }
    return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:这没关系吗?它似乎工作,但我从来没有覆盖alloc.另外,如果没关系,我可以一直使用这种技术,而不是我一直在做的dispatch_once方法吗?...

+ (id)sharedInstance {

    static SnappyTV *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*aFi 5

正如@ H2CO3所提到的,你开始生产单身的方法是可以接受的,但不是线程安全的.更传统的方法是将您的赋值和比较包装在一个@synchronized块中,这样可以减少多线程访问,但是覆盖+alloc不是实现已经不稳定模式的最佳方法.