标签:
保证一个类公有一个实例。并提供一个訪问它的全局訪问点。
1、使用场景
单例的创建有非常多写法,Swift支持仅仅有struct支持静态变量。class不支持静态变量。所以非常easy想到,在类的内部使用struct就能解决引用的保存问题,代码例如以下:
class SwiftSingleton { class var shared: SwiftSingleton { dispatch_once(&Inner.token) { Inner.instance = SwiftSingleton() } return Inner.instance! } struct Inner { static var instance: SwiftSingleton? static var token: dispatch_once_t = 0 } }
class SwiftSingletonTest: XCTestCase { func testSingleton() { let singleton1 = SwiftSingleton.shared let singleton2 = SwiftSingleton.shared assert(singleton1 === singleton2, "pass") } }
class SwiftSingleton { class var shared: SwiftSingleton { return Inner.instance } struct Inner { static let instance = SwiftSingleton() } }
struct SwiftSingleton { var name: String = "1" static let shared = SwiftSingleton() } var single1 = SwiftSingleton.shared var single2 = SwiftSingleton.shared single2.name = "2" println("------->\(single1.name)") println("------->\(single2.name)")
------->1 ------->2 Program ended with exit code: 0
版权声明:本文博客原创文章。博客,未经同意,不得转载。
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/4633957.html