美文网首页
单例在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中的正确姿势

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