为什么在 UIViewPropertyAnimator 中使用 'unowned'

Why use 'unowned' in UIViewPropertyAnimator

所以我一直在阅读有关 UIViewPropertyAnimator 的一些资料,在我一直在看的例子中,他们做了这样的事情:

animator = UIViewPropertyAnimator(duration: 2.0, curve: .easeInOut, animations: { 
        [unowned self, redBox] in
        redBox.center.x = self.view.frame.width
        redBox.transform = CGAffineTransform(rotationAngle: CGFloat.pi).scaledBy(x: 0.001, y: 0.001)
    })

我不明白其中的“[unowned self, redBox]”部分。谁能解释一下我们用它做什么?

我知道 unowned 通常用于决定如何确定引用计数,并且不能将其设置为 nil,因为引用将在没有另一个引用的情况下不存在(作为 weak 的替代方法),但是我不明白这里的用法,我也不明白括号部分。在我看来,它是一组正在制作动画的项目及其所在的视图?

完整代码如下:

import UIKit

class ViewController: UIViewController {

    var animator: UIViewPropertyAnimator!

    override func viewDidLoad() {
        super.viewDidLoad()

        //redBox

        let redBox = UIView(frame: CGRect(x: 10, y: 100, width: 100, height: 100))
        redBox.translatesAutoresizingMaskIntoConstraints = false// lar oss redigere posisjon og sånn selv, uten at xcode setter posisjon/størrelse i stein.
        redBox.backgroundColor = .red
        redBox.center.y = view.center.y

        view.addSubview(redBox)

        animator = UIViewPropertyAnimator(duration: 2.0, curve: .easeInOut, animations: { 
            [unowned self, redBox] in
            redBox.center.x = self.view.frame.width
            redBox.transform = CGAffineTransform(rotationAngle: CGFloat.pi).scaledBy(x: 0.001, y: 0.001)
        })

        // slider

        let slider = UISlider()
        slider.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(slider)
        slider.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        slider.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        slider.addTarget(self, action: #selector(sliderChanged), for: .valueChanged)

    }
    func sliderChanged(_ sender: UISlider){
        animator.fractionComplete = CGFloat(sender.value)
    }

}
  1. 我们需要使用 weakunowned 否则将创建所有权(参考)循环(self => animator = > animations => self).

  2. 我们可以使用unowned而不是weak,因为我们可以确定selfanimator一起销毁并且当self 被释放,动画将不再是 运行。