美文网首页
单例在swift中的正确姿势

单例在swift中的正确姿势

作者: jueyingxx | 来源:发表于2015-12-16 17:05 被阅读65次

1、OC写法

+ (instanceType)sharedSoundTools {
    static EFSoundTools *instance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

2、仿OC写法

class EFSoundTools: NSObject {
        static var instance: EFSoundTools?
        static var oneToken: dispatch_once_t = 0
        class func sharedSoundTools() -> EFSoundTools {
        dispatch_once(&oneToken) { () -> Void in
            instance = EFSoundTools()
        }
        return instance!
    }
}

3、swift写法

static let sharedSoundTools = EFSoundTools()

4、需要自定义构造函数写法

static let sharedTools: EFNetworkTools = {
    let baseURL = NSURL(string: "https://api.weibo.com/")
    let tools = EFNetworkTools(baseURL: baseURL)
    return tools
}()

相关文章

  • 单例在swift中的正确姿势

    1、OC写法 2、仿OC写法 3、swift写法 4、需要自定义构造函数写法

  • Swift小技巧

    Swift简洁,高效的小技巧 1.单例的正确姿势,相比OC,Swift的单例简洁到极致 2.defer语句会推迟包...

  • Swift单例的创建姿势

    Swift单例创建的正确姿势 [来源][http://my.oschina.net/jeans/blog/541750]

  • Swift 单例

    Swift中编写单例的正确方式

  • swift语法-14单例

    swift语法-14单例 OC中单例 Swift中单例 简写 Swift中最长用的方法

  • 单例模式的书写

    ARC OC 中的单例 根据OC单例 改写成 Swift 中的单例 OC调用swift,需要#import "单例...

  • Swift中的单例

    转战swift有几天了,接触到了swift中的单例,下面介绍一下swift中的单例: 仿照OC中的单例的写法,写一...

  • 单例

    内存中只有一个对象实例 提供一个全局访问点 OC中的单例 swift中的单例 swift改进过的单例

  • 你真的会写单例吗?

    你真的会写单例吗? 摘录来源 单例的正确姿势 Java单例模式可能是最简单也是最常用的设计模式,一个完美的单例需要...

  • 用 Swift 架构 iOS 应用的正确姿势

    用 Swift 架构 iOS 应用的正确姿势 用 Swift 架构 iOS 应用的正确姿势

网友评论

      本文标题: 单例在swift中的正确姿势

      本文链接:https://www.haomeiwen.com/subject/mfxphttx.html