不确定我是否正确使用了这个配套对象。
数据类:
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)
}
}
片段生成器类(在此处查找路径管理器配套对象(:
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(( 中正确构建的。数据在那里(可以 在调试器中查看(
路径管理器启动"Frag(("类
Frag(( 类引用回在中创建的配套对象 PathManager((, 尝试在 中查找数据 "PathManager.shared.app?。项目',但其中的数据为空,当 不应该。 伴随对象与静态对象不同吗 变量?
我确定我错过了一些东西,只是在寻找建议。 我是否正确调用了配套对象? 我不能从这样的新类中引用它吗? 什么给?
PathManager.shared.app?.items
始终为空,因为您永远不会将AppModel
分配给伴随对象。 类PathManager
var app: AppModel? = null
实例和PathManager.shared.app
是两个不同的对象。
要存储静态数据,您可以执行以下操作:
open class PathManager() {
companion object {
//Here Don't create object is you dont need it
//var shared = PathManager() // SHARED OBJECT IN QUESTION
//Create AppModel instance.
var mAppModel: AppModel? = null
}
//Comment this as will manage companion object.
//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)
mAppModel = appModel
performInitialPath()
}
private fun performInitialPath() {
val app = app?.let { it } ?: error("Attempted to start without an App Config.")
mAppModel = app // DEBUGGER SHOWS CORRECT VALUES HERE
// Removed irrelevant code for readability, builds 'initialFoo' here
this.mainActivity.addFragment(initialFoo)
}
}
并在其他类中使用它
class Frag : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var itemModels: List<ItemModel>? = null
//Retrive the list from shared object.
if(PathManager.mAppModel?.items != null) { // NULL - WHY?
itemModels = PathManager.mAppModel?.items
}
}
}