Ios 我是否需要在下面的代码中使用捕获列表来避免保留循环?就好像A不直接控制B,B又控制A一样 请看一看。我不确定下面的代码是否有保留周期。

Ios 我是否需要在下面的代码中使用捕获列表来避免保留循环?就好像A不直接控制B,B又控制A一样 请看一看。我不确定下面的代码是否有保留周期。,ios,swift,closures,nsoperationqueue,retain-cycle,Ios,Swift,Closures,Nsoperationqueue,Retain Cycle,我查看了其他与RetainCycle相关的帖子和文章,但仍然不清楚下面的代码。我故意重命名类和其他东西 import UIKit class SomeInterface { var queue: OperationQueue? private static var sharedInterface: SomeInterface = SomeInterface() class func getInterface() -> SomeInterface {

我查看了其他与RetainCycle相关的帖子和文章,但仍然不清楚下面的代码。我故意重命名类和其他东西

import UIKit

class SomeInterface {
    var queue: OperationQueue?
    private static var sharedInterface: SomeInterface  = SomeInterface()

    class func getInterface() -> SomeInterface {
        return sharedInterface
    }

    init() {
        queue = OperationQueue()
    }
    class func add(toQueue block : @escaping ()->Void) {
        SomeInterface.getInterface().queue?.addOperation(block)
    }
    func someWork() {
        print("some work")
    }
    deinit {
        print("deinitlized")
    }
}

// Here instance of SomeInterface holding strong reference to **queue**, And //**queue** retains the closure and closure eventually capture "**self**" 
class InterfaceCore {
    class func executeSomeWork() {
        SomeInterface.add(toQueue: { // Should I use capture list here?
            SomeInterface.getInterface().someWork()
        })
    }
}

InterfaceCore.executeSomeWork() // Would it create retain cycle?

//如果是,我是否正在使用捕获列表进行更正

class InterfaceCore {
    class func executeSomeWork() {
        SomeInterface.add(toQueue: { [weak weakInterface = SomeInterface.getInterface() ] in
            if let _ = weakInterface {
                SomeInterface.getInterface().someWork()
            }
        })
    }
}

这里没有保留循环。您可以通过在
sharedInterface
上调用
isKnownUniquelyReferenced
来确认这一点,以查看它是否持有对共享实例的唯一引用


闭包尤其不会捕获接口,因为它是通过
getInterface
获取接口的,而不是首先存储对接口的引用。

这里没有保留循环。您可以通过在
sharedInterface
上调用
isKnownUniquelyReferenced
来确认这一点,以查看它是否持有对共享实例的唯一引用

闭包尤其不会捕获接口,因为它是通过
getInterface
获取接口的,而不是首先存储对接口的引用