IOS swift项目的单例模式.swift5以后的单例模式
不能继承NSObject 第一种写法,最简单
class SoundTools{
static let sharedInstance = SoundTools()
private init() { }
第2种写法
class SoundTools{
class var sharedInstance2: SoundTools {
struct Static {
static let inst: SoundTools = SoundTools()
}
return Static.inst
}
}
在打印地方,写一个打印地址的函数,否则print函数无法打印地址
func address<T: AnyObject>(o: T) -> String {
return String.init(format: "%018p", unsafeBitCast(o, to: Int.self))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print(address(o: SoundTools.sharedInstance))
print(address(o: SoundTools.sharedInstance2))
print(address(o: Peson()))
print("===")
}
看看控制台输出
0x00006000016f0f20
0x00006000016ec170
0x00006000016ec180
===
0x00006000016f0f20
0x00006000016ec170
0x00006000016f0eb0
===
证明单例没有问题
|