semaphore_wait_trap when accessing class singleton using Swift

objective-c, swift, xcode

Solution

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.

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

Problem

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") } } ``` In this case it is calling it from within the `init` of itself, but it happens elsewhere. The code never gets to `test 2`. As soon as it access `MyManager.sharedInstance` it hangs. No errors or warnings. If I pause the debugger I can see it is currently having on `semaphore_wait_trap` Picture (difference class names): Restarting Xcode or the computer hasn't helped.

Original source