ios下比较完美的单例模式


【原】ios下比较完美的单例模式,已验证

网上关于ios单例模式实现的帖子已经很多了,有很多版本,里面有对的也有不对的。我在使用过程中很难找到一个比较完美的方法,索性自己写一个吧,经过项目验证是比较合理的一个版本。

复制代码
static PRAutoLoginView *s_sharedInstance = nil;
+ (PRAutoLoginView *)shareInstance
{
    @synchronized(self)
    {
        if (s_sharedInstance == nil) {
            s_sharedInstance = [[[self class] hideAlloc] init];
        }
    }
    return s_sharedInstance;
}

#pragma mark --
#pragma mark singleton apis
+ (id)hideAlloc
{
    return [super alloc];
}

+ (id)alloc//彻底屏蔽掉alloc函数
{
    NSAssert(1 == 0, @"[PRAutoLoginView]please use +shareInstance instead of alloc!");
    return nil;
}

+ (id)new
{
    return [self alloc];
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self)
    {
        if (s_sharedInstance == nil) {
            s_sharedInstance = [super allocWithZone:zone];
            return s_sharedInstance;
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    NSAssert(1 == 0, @"[PRAutoLoginView]copy is not permitted!");
    [self retain];
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    return [self copyWithZone:zone];
}
复制代码

这里要注意的一点时,allocWithZone时默认调用的,即使你没有显式地调用alloc或者allocWithZone,因此需要重载


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值