compiler forcing self inside static method of a fu

2019-09-06 07:43发布

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()

标签: swift
1条回答
干净又极端
2楼-- · 2019-09-06 07:56

The problem is not about dispatch_async, but it's because you are referencing self 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 that self is captured by mistake, swift requires that self 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 using self 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

查看更多
登录 后发表回答