Closures
Closures copied to clipboard
Clear handler?
Example
button.onTap(handler:{
// do stuff
})
How do I clear this handler to avoid a leak when my VC is deallocated?
See here: https://stablekernel.com/how-to-prevent-memory-leaks-in-swift-closures/#toc_2.
button.onTap(handler:{ [weak self] in
self?.doStuff()
})
So there is no way to clear the handler on the button?
If you can help me understand the problem, I'll be able to help you and also help myself in order to provide the best solution for your (and other's) use case.
It just simply uses target-action, so everything is weakly held. The closure will stay around as long as you have the button strongly held by your VC, just the way that a target-action handler stays around when you use @IBAction
or something.
If all you want to do is remove the handler, there are a few ways to do that right now as a work-around:
button.removeTarget(nil, action: nil, for: .touchUpInside)
//removes all touch up inside events
button.onTap {}
//sets the handler to do nothing
Let me know if this works or maybe what you're trying to accomplish and I'll try to assist as best I can.
i think he is talking about the .removeTarget.
for example
button.onTap { [weak self] in self?.loadData() } button.onTap { [weak self] in self?.loadData() }
if we tap the button, we load the data twice, right?
Ah ok. Yes, I just saw this bug yesterday and fixed it. Please upgrade to v0.3, as it is fixed there.
I will leave this issue open, however, because I think it would be beneficial to have an explicit way to remove the handlers.
Good find, and thanks for the feedback!
Actually I was saying if I can do this
button.onTap(handler:{
// do stuff
})
then I would like to do this
button.removeOnTapHandler()
Hello Any news on this? I would like the block to be deleted when the object is deleted without additional code
Objects are removed without additional code. This issue is for an enhancement to have it explicitly removed. If you are having those types of issues you'll have to post a new issue with your code so we can take a look. Likely it may be a retain cycle in your closure handler (retaining self typically).