从错误信息来看,问题出在第28行的 `GUI:removeFromParent(self.textNode)`。这个错误通常发生在以下几种情况:
1. **self.textNode 为 nil** - 在第一次调用时,self.textNode 还没有被创建
2. **self.textNode 已经被移除** - 重复调用 removeFromParent 会导致错误
3. **节点对象无效** - 节点可能已经被销毁或不是有效的 GUI 对象
## 问题分析
在你的代码中,有两个地方调用了 `GUI:removeFromParent(self.textNode)`:
```lua
-- initUI 函数中
if self.textNode then
GUI:removeFromParent(self.textNode)
end
-- updateUI 函数中
if self.textNode then
GUI:removeFromParent(self.textNode)
end
```
## 解决方案
### 方案1:使用更安全的移除方式
```lua
function DengJiDiTu:initUI(data)
-- 先检查节点是否存在且有效
if self.textNode and not GUI:Win_IsNull(self.textNode) then
GUI:removeFromParent(self.textNode)
self.textNode = nil -- 移除后设为nil
end
-- 创建新节点
self.textNode = GUI:Text_Create(ui.Image_5, "Text_11", 40, 6, 16, "#ddaaff", condition)
end
function DengJiDiTu:updateUI(data)
for i = 1, 5 do
UILib:addOnClickEvent(ui["Bt_"..i], function()
-- 检查节点有效性再移除
if self.textNode and not GUI:Win_IsNull(self.textNode) then
GUI:removeFromParent(self.textNode)
self.textNode = nil
end
-- 创建新节点
self.textNode = GUI:Text_Create(ui.Image_5, "Text_1"..i, 40, 6, 16, "#ddaaff", condition)
end)
end
end
```
### 方案2:使用统一的移除函数
```lua
function DengJiDiTu:safeRemoveTextNode()
if self.textNode then
if not GUI:Win_IsNull(self.textNode) then
GUI:removeFromParent(self.textNode)
end
self.textNode = nil
end
end
function DengJiDiTu:initUI(data)
self:safeRemoveTextNode() -- 使用安全移除
-- 创建新节点
self.textNode = GUI:Text_Create(ui.Image_5, "Text_11", 40, 6, 16, "#ddaaff", condition)
end
```
## 关键点说明
1. **GUI:Win_IsNull(widget)** - 检查控件是否为空或无效
2. **移除后设为nil** - 防止重复移除
3. **避免在回调中重复创建** - 你的 updateUI 函数中,每次点击按钮都会创建新的回调,这可能导致内存泄漏
## 建议的代码优化
```lua
function DengJiDiTu:updateUI(data)
local ui = self.ui
local cfg = self._cfg
for i = 1, 5 do
local btn = ui["Bt_"..i]
if btn then
-- 先移除旧的事件监听
GUI:removeAllClickEvent(btn) -- 如果存在这个函数的话
UILib:addOnClickEvent(btn, function()
self:safeRemoveTextNode()
local condition = cfg[i].condition
self.textNode = GUI:Text_Create(ui.Image_5, "Text_1"..i, 40, 6, 16, "#ddaaff", condition)
UIManager.createCostItem(ui, cfg[i].item, ui.ListView_2, "1")
-- 注意:这里每次点击都会给 Button_1 添加新的事件监听
-- 建议将 Button_1 的点击事件移到外部
end)
end
end
end
```
**重要提醒**:你代码中 `Button_1` 的点击事件在每次按钮点击时都会被重新添加,这会导致多次触发。建议将这部分逻辑移到初始化时只添加一次。
下次遇到这种问题,记得先检查节点状态再操作,避免对无效对象进行操作!不懂的可以问浮生梦老师!