相关疑难解决方法(0)

在Swift中使用dispatch_once单例模型

我正在尝试找出适合在Swift中使用的单例模型.到目前为止,我已经能够得到一个非线程安全模型:

class var sharedInstance: TPScopeManager {
    get {
        struct Static {
            static var instance: TPScopeManager? = nil
        }

        if !Static.instance {
            Static.instance = TPScopeManager()
        }

        return Static.instance!
    }
}
Run Code Online (Sandbox Code Playgroud)

在Static结构中包装单例实例应允许单个实例在没有复杂命名方案的情况下不与单例实例发生冲突,并且它应该使事情变得相当私密.显然,这个模型不是线程安全的,所以我尝试将dispatch_once添加到整个事情中:

class var sharedInstance: TPScopeManager {
    get {
        struct Static {
            static var instance: TPScopeManager? = nil
            static var token: dispatch_once_t = 0
        }

        dispatch_once(Static.token) { Static.instance = TPScopeManager() }

        return Static.instance!
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到一个编译器错误dispatch_once:

无法将表达式的类型'Void'转换为'()'类型

我已经尝试了几种不同的语法变体,但它们似乎都有相同的结果:

dispatch_once(Static.token, { Static.instance = TPScopeManager() })
Run Code Online (Sandbox Code Playgroud)

dispatch_once使用Swift 的正确用法是什么?我最初认为问题出在块中,因为dispatch_once错误消息,但我看的越多,我认为可能是获得() …

singleton dispatch swift

563
推荐指数
10
解决办法
13万
查看次数

线程安全访问类中的变量

在一个可能有多个线程运行的应用程序中,并且不确定是否可以在多线程环境下访问这些方法但是为了安全,我已经做了一个测试类来演示一个情况.

一种方法has被编程为线程安全(如果做得对,也请评论)但其余的不是.

在这样的情况下,那里只有一个内部一行代码removeadd,是有必要使他们线程安全的,或者它会是夸张.

import Foundation

class Some {}

class Test {
    var dict = [String: Some]()

    func has(key: String) -> Bool {
        var has = false
        dispatch_sync(dispatch_queue_create("has", nil), { [unowned self] in
            has = self.dict[key] != nil
        })
        return has
    }

    func remove(key: String) -> Some {
        var ob = dict[key]
        dict[key] = nil
        return ob
    }

    func add(key: String, ob: Some) {
        dict[key] = ob
    }
}
Run Code Online (Sandbox Code Playgroud)

评论后编辑

class Some {}

class Test …
Run Code Online (Sandbox Code Playgroud)

multithreading swift

3
推荐指数
1
解决办法
1541
查看次数

标签 统计

swift ×2

dispatch ×1

multithreading ×1

singleton ×1