单例模式,在OC和Swift中的写法
1)**oc中实现创建时都会默认调用的allocwithzone**
static id _instance;
//重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
2)**swift中,可以使用static来定义共享单例,并且关闭init**
class HLTestObject: NSObject {
var height = 10;
var arrayM: NSMutableArray
var object: NSObject
static let sharedInstance = HLTestObject();
private override init() {
object = NSObject()
arrayM = NSMutableArray()
super.init()
}
}
3)**swift中,使用dispatch\_once来执行只需运行一次的线程安全代码**
GCD实践(三)[http://zhangbuhuai.com/using-gcd-part-3/](https://www.gitbook.com/book/edokonan/swift/edit#)
static SampleSingleton *_sharedInstance = nil;
+ (SampleSingleton *)sharedManager
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[SampleSingleton alloc] init];
});
return _sharedInstance;
}