Singleton.h
//// Singleton.h// SingletonDemo//// Created by zhanggui on 15/8/6.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import <Foundation/Foundation.h>@interface Singleton : NSObject+(instancetype)sharedInstance;@end
Singleton.m
//// Singleton.m// SingletonDemo//// Created by zhanggui on 15/8/6.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "Singleton.h"@implementation Singleton+(instancetype)sharedInstance { static Singleton *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance;}@end
上面這種方式是最安全也是最有效的創建單例的方式。不可能去創建兩個實例,而且使100%的線程安全。
新聞熱點
疑難解答