gpt4 book ai didi

swift - 类似于闭包的弱var之类的东西

转载 作者:行者123 更新时间:2023-11-30 11:29:29 26 4
gpt4 key购买 nike

我该如何修复这个代码,不阻止对象

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)

最佳答案

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

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

关于swift - 类似于闭包的弱var之类的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50402707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com