iOS单例

在iOS开发中单例用的非常普遍,比如说通知中心,NSUserDefauld等都都是单例模式,原来以为创建一个单例是很简单的事情。直接用GCD来搞定。

+ (instancetype)shared
{
    static dispatch_once_t once = 0;
    static Class *singleton;
    dispatch_once(&once, ^{
        alert = [[Class alloc] init];
    });
    return singleton;
}

这样就搞定了,今天忽然被问到怎么避免通过自带的alloc来进行实例化,这样就不能保证单例了。

那么只要把alloc都禁止使用就可以了,所以我们需要重写系统提供的各种alloc方法来避免这种情况。

我们来稍微改造一下


+ (instancetype)hiddenAlloc
{
    return [super alloc];
}

+ (instancetype)alloc
{
    NSAssert(NO, @"请使用shared方法");
    return nil;
}
+ (instancetype)new
{
    return [self alloc];
}

+ (instancetype)shared
{
    static dispatch_once_t once = 0;
    static HHAlertView *alert;
    dispatch_once(&once, ^{
        alert = [[HHAlertView hiddenAlloc] init];
    });
    return alert;
}

以上重载了alloc、allocWithZone和new方法,让其不能调用父类的alloc方法,然后创建我们的私有alloc方法,在alloc方法中加上断言来提醒。

以上就可以解决问题。

你可能感兴趣的:(iOS单例)