如果未从已销毁的活动中删除,侦听器是否会创建内存泄漏? [英] Do listeners create memory leaks if not removed from a destroyed activity?
问题描述
如果您向控件/视图添加侦听器而不删除它,是否会创建内存泄漏?例如, onCreate
将一个侦听器添加到侦听修改的 EditText
。你需要在onDestroy中删除这个监听器吗?
If you add a listener to a control/view and do not remove it, will that create a memory leak? For example, onCreate
adds a listener to an EditText
that listens for modifications. Do you need to remove this listener in the onDestroy?
我想如果你使用匿名监听器或实现监听器的局部变量,内存将是免费的' d当由于范围规则而销毁活动
时。
I imagine that if you use an anonymous listener or a local variable that implements the listener, the memory would be free'd when the Activity
is destroyed due to scoping rules.
我能看到内存泄漏的唯一方法是如果侦听器是在intent对象中传递的。想法?
The only way I could see a memory leak potential is if the listener was passed in an intent object. Thoughts?
推荐答案
监听器本身不会造成内存泄漏。但是,它们经常使用不当,因此可能导致泄漏。有时你会看到一个对象引用一个组件的代码(例如用于在那里显示消息),它有一个监听器,它可以(可能间接地)引用第一个对象。这形成了一个循环,其所有成员共同生活和死亡。当组件是一个短命的对话框时,您可能会遇到问题。初学者倾向于使用像
By themselves, listener do not create a memory leak. However, they're often used improperly and so may lead to leaks. Sometimes you see code where an object refers to a Component (e.g. for displaying messages there), which has a listener, which refers (possibly indirectly) to the first object. This forms a cycle and all its members live and die together. When the Component is a dialog which is meant to be short-living, you may have a problem. Beginners tend to use objects like
class MyKitchenSink implements Runnable, KeyListener, ....
可能有很多引用,并且更容易构建内存泄漏 * 。不创建通用类是要走的路。
which may have a lot of references and makes it easier to build a memory leak*. Not creating "universal classes" is the way to go.
* 这不是真实的内存泄漏,如 C
,因为所有对象都可以访问,如果你愿意可以使用。它只是让对象可以在比预期更长的时间内到达,这就像泄漏一样让你感到内存。
* It's no "real" memory leak like in C
, since all the objects stays reachable and could be used if you wanted to. It's just keeping object reachable for a much longer time than expected, which eats you memory just like a leak.
这篇关于如果未从已销毁的活动中删除,侦听器是否会创建内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!