ios-UI高階多執行緒 GCD實現單例模式

A_StayFoolish發表於2016-08-05
1、單例模式
· 單例模式的作用
a) 可以保證在程式執行過程,一個類只有一個例項,而且該例項易於外界訪問
b) 可以方便的控制例項個數,節約系統資源
· 單例模式的使用場合

c) 在整個應用程式中,共享一份資源(只需初始化建立一次)


2、GCD中單例模式的實現

#import "Person.h"


@interface Person() <NSCopying>


@end


@implementation Person


// 靜態例項(只能在本檔案中使用)

static Person *_person;

// 重寫allocWithZone:方法

+(instancetype)allocWithZone:(struct _NSZone *)zone{

    

    static dispatch_once_t onceType;

    dispatch_once(&onceType, ^{

        _person = [super allocWithZone:zone];

    });

    return _person;

}


// 只初始化一次例項

+(instancetype)share{

    static dispatch_once_t onceType;

    dispatch_once(&onceType, ^{

        _person = [[self alloc]init];

    });

    return _person;

}


//copy方法

-(instancetype)copyWithZone:(NSZone *)zone{

    return _person;

}


@end



相關文章