如何修复此代码, 不阻止对象
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)
答案 0 :(得分:0)
不是直接传递对controller
方法的引用,而是将其包装在闭包中。
... handle: { [weak controller] button in controller?.buttonAction(button) })