Closures icon indicating copy to clipboard operation
Closures copied to clipboard

Clear handler?

Open MKGitHub opened this issue 7 years ago • 8 comments

Example

button.onTap(handler:{
    // do stuff
})

How do I clear this handler to avoid a leak when my VC is deallocated?

MKGitHub avatar Oct 21 '17 14:10 MKGitHub

See here: https://stablekernel.com/how-to-prevent-memory-leaks-in-swift-closures/#toc_2.

button.onTap(handler:{ [weak self] in
    self?.doStuff()
})

vhesener avatar Oct 21 '17 15:10 vhesener

So there is no way to clear the handler on the button?

MKGitHub avatar Oct 21 '17 23:10 MKGitHub

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.

vhesener avatar Oct 22 '17 00:10 vhesener

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?

smiLLe avatar Oct 24 '17 09:10 smiLLe

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!

vhesener avatar Oct 24 '17 15:10 vhesener

Actually I was saying if I can do this

button.onTap(handler:{
    // do stuff
})

then I would like to do this

button.removeOnTapHandler()

MKGitHub avatar Oct 24 '17 18:10 MKGitHub

Hello Any news on this? I would like the block to be deleted when the object is deleted without additional code

nikmoiseev avatar Jul 22 '19 11:07 nikmoiseev

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).

vhesener avatar Aug 01 '19 04:08 vhesener