使用 Swift 访问类单例时的 semaphore_wait_trap [英] semaphore_wait_trap when accessing class singleton using Swift

查看:33
本文介绍了使用 Swift 访问类单例时的 semaphore_wait_trap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题.我可以很好地访问我的类单例实例,但是如果我再次尝试访问它,它似乎挂起.这是代码的简单版本:

I'm running into a strange problem. I can access my classes singleton instance just fine, but if I try to access it again it just appears to hang. Here is a simple version of the code:

private let _SharedInstance = MyManager()

class MyManager: NSObject {

    class var sharedInstance: MyManager {
        return _SharedInstance
    }

    override init() {
        super.init()

        println("init")

        println(self.accessToken())
        println(MyManager)
        println("test 1")
        println(MyManager.sharedInstance)
        println("test 2")
    }

}

在这种情况下,它从自身的 init 内部调用它,但它发生在其他地方.

In this case it is calling it from within the init of itself, but it happens elsewhere.

代码永远不会进入test 2.一旦它访问 MyManager.sharedInstance 它就会挂起.没有错误或警告.

The code never gets to test 2. As soon as it access MyManager.sharedInstance it hangs. No errors or warnings.

如果我暂停调试器,我可以看到它当前在 semaphore_wait_trap

If I pause the debugger I can see it is currently having on semaphore_wait_trap

图片(不同的类名):

重新启动 Xcode 或计算机没有帮助.

Restarting Xcode or the computer hasn't helped.

推荐答案

创建 MyManager 时,会使用锁来防止其他线程在创建变量时访问该变量.您无法从 init 方法中访问此变量.不仅仅是似乎挂起你的程序,它每次都会挂起你的程序,因为你正在制造一个死锁.

When MyManager gets created, a lock is used to prevent other threads from accessing the variable while it is being created. You cannot access this variable from within the init method. It doesn't just seem to hang your program, it will every single time hang your program because you are creating a deadlock.

解决方案:不要在 init 方法中使用该变量.不要直接或间接从 init 方法访问 _SharedInstance.

Solution: Don't use that variable from your init method. Don't access _SharedInstance from your init method, directly or indirectly.

这篇关于使用 Swift 访问类单例时的 semaphore_wait_trap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆