objective-c 单例模式Singleton的实现

<span style="background-color: rgb(255, 255, 255);">Update:</span>
<span style="background-color: rgb(255, 255, 255);">如下评论中 脱离语言 所说oc单例实现采用如下形式:</span>
+ (NetworkManager *)sharedInstance
{
    static dispatch_once_t onceToken;
    static NetworkManager * sSharedInstance;

    dispatch_once(&onceToken, ^{
        sSharedInstance = [[NetworkManager alloc] init];
    });
    return sSharedInstance;
}
</span>
<span style="background-color: rgb(255, 255, 255);">
</span>
<span style="background-color: rgb(255, 255, 255);"><a target=_blank href="http://yulingtianxia.com/blog/2014/04/07/iosdan-li-mo-shi-ornsuserdefaults/">这篇博客</a>对单例模式做了详细的介绍,下面的单例实现方式并不完善,可直接略过。</span>
<span style="background-color: rgb(255, 255, 255);">
</span>
static ClubSession *_singletonInstance = nil;

+ (ClubSession *)current
{
    @synchronized(self)
    {
        if (_singletonInstance == nil) {
            _singletonInstance = [[ClubSession alloc] init];
        }
        return _singletonInstance;
    }
}


The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time. In this case, however, you do not have to create the mutex or lock object directly. Instead, you simply use any Objective-C object as a lock token, as shown in the following example:

- (void)myMethod:(id)anObj
{
    @synchronized(anObj)
    {
        // Everything between the braces is protected by the @synchronized directive.
    }
}

The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block. If you execute the preceding method in two different threads, passing a different object for the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. If you pass the same object in both cases, however, one of the threads would acquire the lock first and the other would block until the first thread completed the critical section.

As a precautionary measure, the @synchronized block implicitly adds an exception handler to the protected code. This handler automatically releases the mutex in the event that an exception is thrown. This means that in order to use the @synchronized directive, you must also enable Objective-C exception handling in your code. If you do not want the additional overhead caused by the implicit exception handler, you should consider using the lock classes.


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值