像闭包的弱变量一样

时间:2018-05-18 01:50:49

标签: swift

如何修复此代码, 不阻止对象

class EIUIBarButtonItem: UIBarButtonItem {
    typealias HandleClosure = (UIBarButtonItem) -> Void
    fileprivate var handle: HandleClosure?
    init(image: UIImage?, style: UIBarButtonItemStyle, handle: HandleClosure? = nil) {
        self.handle = handle
        super.init()
        self.image = image
        self.style = style
        self.target = self
        self.action = #selector(buttonAction(_:))
    }
    // ...OtherCode...        
    @objc func buttonAction(_ sender: UIBarButtonItem) {
        handle?(sender)
    }
}

如果我将此按钮创建为

EIUIBarButtonItem(image: myUIImage, style: .plain, handle: controller.buttonAction)

我对象controller。我怎么能这样做?我的手柄需要弱变量

   weak var handle: HandleClosure?

或者类似的东西(@unowned)

   EIUIBarButtonItem(image: myUIImage, style: .plain, handle: @unowned controller.buttonAction)

1 个答案:

答案 0 :(得分:0)

不是直接传递对controller方法的引用,而是将其包装在闭包中。

... handle: { [weak controller] button in controller?.buttonAction(button) })