(有碼)創建單例

#import "Person.h"

//全局的靜態變量,要創建的單例類型的
static Person *person;
@implementation Person

//快速創建方式
+ (id)person{
    if (person == nil) {
        /**
         *  dispatch_once的作用正如其名,對於某個任務執行一次,並且只執行一次。有兩個參數,第一個onceToken用來保證只執行一次,第二個參數block裏的要執行的任務
            dispatch_once在多線程程序用被廣泛應用,可靠簡單
         */
        static dispatch_once_t once;
        dispatch_once(&once, ^{
            person = [super alloc];
            person = [person init];
        });
    }
    return person;
}

//調用alloc方法就會調用該方法
+ (id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        person = [super allocWithZone:zone];
    });
    return person;

}


//打印信息地址相同

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person *per = [Person person];
    NSLog(@"%@", per);
    Person *person1 = [[Person alloc] init];
    NSLog(@"%@", person1);
    
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章