Swift基础篇——单例

单例

import Foundation

class NetWorkingTools:NSObject {

    //    func == -
    //    class func == +

    // 方法一:
    /*
    static var onceToken: dispatch_once_t = 0;
    static var _instance: NetworkTools?

    class func shareNetworkTools() -> NetworkTools {
    print(onceToken)
    dispatch_once(&NetworkTools.onceToken, {
    _instance = NetworkTools()
    })
    return _instance!
    }
    */

    // 方法二:
    /*
    static let _instance: NetworkTools =  NetworkTools()
    class func shareNetworkTools() -> NetworkTools {
    return _instance
    }
    override init() {
    print("++++++")
    }
    */

    // 方法三:
    // 如果在Swift中编写单例, 推荐使用如下写法
    // 而且苹果有统一的命名规范, 但凡是单例统一是用shareInstance
    static let shareInstance: NetWorkingTools = NetWorkingTools()
}

你可能感兴趣的:(iOS那些事)