不确定我是否正确使用此伴侣对象 .
数据类:
data class AppModel(
val name: String,
val items: List<ItemModel>,
)
设置数据:
open class PathManager() {
companion object {
var shared = PathManager() // SHARED OBJECT IN QUESTION
}
var app: AppModel? = null
fun setUp() {
// Show loading...
// Parse the JSON
val gson = GsonBuilder().create()
val text = mainActivity.resources.openRawResource(R.raw.jsonFile)
.bufferedReader().use { it.readText() }
val appModel = gson.fromJson(text, AppModel::class.java)
app = appModel
performInitialPath()
}
private fun performInitialPath() {
val app = app?.let { it } ?: error("Attempted to start without an App Config.")
this.app = app // DEBUGGER SHOWS CORRECT VALUES HERE
// Removed irrelevant code for readability, builds 'initialFoo' here
this.mainActivity.addFragment(initialFoo)
}
}
Fragment Builder Class(在这里查找Path Manager伴随对象):
class Frag : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var itemModels: List<ItemModel>? = null
if(PathManager.shared.app?.items != null) { // NULL - WHY?
itemModels = PathManager.shared.app?.items
}
}
}
总结一下发生了什么:
-
AppModel在PathManager()中正确构建 . 那里有数据(可以在调试器中看到)
-
Path Manager启动'Frag()'类
-
Frag()类引用返回在PathManager()中创建的伴随对象,尝试在“PathManager.shared.app?.items”中查找数据,但其中的数据为空时,不应该为空 . 伴随对象不是静态变量吗?
我确信我错过了一些东西,只是寻求建议 . 我是否正确调用了伴侣对象?我不能从像这样的新类中引用它吗?是什么赋予了?
1 回答
PathManager.shared.app?.items
始终为null,因为您永远不会将AppModel
分配给随播对象 .PathManager
中的var app: AppModel? = null
实例和PathManager.shared.app
是两个不同的对象 .要存储静态数据,您可以执行以下操作:
并在其他类中使用它