Following code works but I was forced by the compiler to use self inside dispatch_sync
, IMO I believe self
isn't created yet and shouldn't be accessible. why self inside a static function?
I was trying to use this way instead
dispatch_sync(queue, {
if (object == nil) {
object = SingleObject()
}
})
return object!
working version
import Foundation
public class SingleObject {
public struct Static {
private static var object: SingleObject?
public static func getObject() -> SingleObject {
let queue = dispatch_queue_create("queue", nil)
dispatch_sync(queue, {
if (self.object == nil) {
self.object = SingleObject()
}
})
return object!
}
}
}
SingleObject.Static.getObject()
The problem is not about
dispatch_async
, but it's because you are referencingself
in a closure.Whenever
self
is used in a closure, it is captured as a strong reference. That can potentially cause a strong reference cycle - to prevent thatself
is captured by mistake, swift requires thatself
is explicitly used when accessing properties and methods.Note that
self
is defined in a static context, and refers to the type rather than an instance. So usingself
in a static method lets you access all static properties and methods defined in the same class/struct.For more info, read Automatic Reference Counting