單例類

weixin_34054866發表於2016-07-02
#import <Foundation/Foundation.h>

@interface Single : NSObject
@property (nonatomic,copy)NSString *value;
+(Single *)SingleModel;
@end

#import "Single.h"
@implementation Single
static Single *single =nil;
+ (Single *)SingleModel
{
    //block內程式碼只會被執行一次 是否被執行 是由once來記錄
    static dispatch_once_t once;
        dispatch_once(&once, ^{
            single =[[Single alloc] init];
        });
    return single;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        single =[super allocWithZone:NULL];
    });
    return single;
}

另外 兩種加鎖方式

@implementation Single
static Single * single =nil;
+ (Single *)SingleModel
{
    //@synchronized 資源保護鎖 防止多執行緒操作時 對同一資源訪問時造成資源混亂而設定的
    //()標示符 代表類  或者使用物件型別  一般使用self
    @synchronized (self)
    {
        if (single==nil)
        {
            single =[[Single alloc] init];
        }
    }
    return single;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
    //NSLock 一種加鎖的形式 和 @synchronized (self)效果一樣
    if (single ==nil)
    {
        NSLock *lock =[[NSLock alloc] init];
        //[lock lock]和[lock unlock]之間的程式碼就是要保護的資源
        [lock lock];
        single = [super allocWithZone:NULL];
        [lock unlock];
    }
    return single;
}

相關文章