为什么我必须在 onLoaderReset 中使用 swapCursor(null)?

why do I have to swapCursor(null) in onLoaderReset?

Android 的文档 (https://developer.android.com/guide/components/loaders.html) 说当我使用加载程序进行 SQL 查询时,我 应该在 onLoaderReset 方法中执行 swapCursor(null):

onLoaderReset This method is called when a previously created loader is being reset, thus making its data unavailable. This callback lets you find out when the data is about to be released so you can remove your reference to it.
This implementation calls swapCursor() with a value of null:

// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
...
public void onLoaderReset(Loader<Cursor> loader) {
    // This is called when the last Cursor provided to onLoadFinished()
    // above is about to be closed.  We need to make sure we are no
    // longer using it.
    mAdapter.swapCursor(null);
}

我不明白为什么要在onLoaderReset 中将adapter 的光标切换为null。据我所知,加载程序在 activity 被销毁时重置。但是当 activity 被销毁时, 它符合垃圾回收条件,并且此 activity 保留的所有引用也符合垃圾回收条件。所以这些适配器中的任何一个都没有关系 保留对游标的引用 - 它不会阻止游标被垃圾收集。

那么,为什么我应该在 onLoaderReset 中将适配器的光标交换为 null?

如果活动的底层成员在 activity 之外引用,活动将不会被垃圾回收。当它的所有成员将来都可能不被使用时,它将被垃圾收集。
if swapCursor(null); 将删除游标的所有基础引用。否则它会创建一个 memory leak 而你的 activity 将不会被垃圾收集。