Swift Closures - Capturing self as weak

后端 未结 3 1736
春和景丽
春和景丽 2020-12-29 09:32

I am trying to resolve a closure based strong reference cycle in Swift.
In the code below, object is retained by the owning view controller. ProgressHUD is

3条回答
  •  清酒与你
    2020-12-29 10:23

    If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles. source Apple

    source sketchyTech First, it is important to make clear that this whole issue only concerns closures where we are assigning "a closure to a property of a class instance". Keep this in mind with each rule. The rules:

    1. use weak capture if the class instance or property is an optional
    2. use unowned if the class instance or property is non-optional and can never be set to nil
    3. "you must ... use the in keyword, even if you omit the parameter names, parameter types, and return type"

    In answear to your question there should be no retain cycle.

提交回复
热议问题