NSCache在swift代码中不是线程安全的吗?

时间:2016-08-19 07:09:36

标签: ios swift

我不确定Swift中的这个线程是不安全的,输出应该是31个字符,是不是NSCache不是线程安全的?

let nscache = NSCache()
nscache.setObject("", forKey: "1")

let globalQueue = dispatch_get_global_queue(0, 0)
dispatch_async(globalQueue) {
    print(NSThread.currentThread())

    for i in 0...10 {

        let str = nscache.objectForKey("1") as! String + ".\(i)"
        nscache.setObject(str, forKey: "1")
        print("str:\(str)")
    }
}

dispatch_async(globalQueue) {
    print(NSThread.currentThread())

    for i in 11...20 {

        let str = nscache.objectForKey("1") as! String + ".\(i)"
        nscache.setObject(str, forKey: "1")
        print("str:\(str)")
    }
}

dispatch_async(globalQueue) {
    print(NSThread.currentThread())

    for i in 21...30 {

        let str = nscache.objectForKey("1") as! String + ".\(i)"
        nscache.setObject(str, forKey: "1")
        print("str:\(str)")
    }
}

输出

  

/////////////////打印/////////////////

     

str:.21 str:.21.11 str:.21.11.0 str:.21.11.0.22 str:.21.11.0.22.12   str:.21.11.0.22.12.1 str:.21.11.0.22.12.1.23   str:.21.11.0.22.12.1.23.13 str:.21.11.0.22.12.1.23.13.24   str:.21.11.0.22.12.1.23.13.2 str:.21.11.0.22.12.1.23.13.2.14   str:.21.11.0.22.12.1.23.13.2.25 str:.21.11.0.22.12.1.23.13.2.3   str:.21.11.0.22.12.1.23.13.2.3.15 str:.21.11.0.22.12.1.23.13.2.3.15.26   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.5   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.29   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7.19   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7.19.30   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7.19.30.8   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7.19.30.8.20   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7.19.30.8.20.9   STR:.21.11.0.22.12.1.23.13.2.3.15.26.4.16.27.17.6.28.18.7.19.30.8.20.9.10

0 个答案:

没有答案