2016-2-20 Swift和Objective-C中的单例

Objective-C中单例的使用姿势:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
+(instancetype)sharedXMPPManager{
static XMPPManager *_instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static XMPPManager *_instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}

那么Swift中该如何写呢,首先给出一种模仿OC的写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import UIKit
class XMPPManager: NSObject {
static var onceToken :dispatch_once_t = 0
static var instance :XMPPManager?
class func sharedXMPPManager()->XMPPManager {
dispatch_once(&onceToken) { () -> Void in
instance = XMPPManager()
}
return instance!
}
}

由于let在Swift中是线程安全的,所以又有以下这种写法,也应该是通用写法了:

1
2
3
4
5
6
7
8
9
10
11
import UIKit
class XMPPManager: NSObject {
static let instance : XMPPManager = XMPPManager()
class func sharedXMPPManager()->XMPPManager {
return instance
}
}
调用方式:XMPPManager.sharedXMPPManager()

而后,我又在Alamofire中发现另外一种写法,效果类似于上面,不过他是以属性的方式提供,

1
2
3
4
5
6
7
8
import UIKit
class XMPPManager: NSObject {
internal static let sharedInstance:XMPPManager = XMPPManager()
}
调用方式:XMPPManager.sharedXMPPManager

大概就这样了,暂做记录。


注:版权声明:本文为博主原创文章,未经博主允许不得转载。