You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xcode中从Firebase文件夹获取标题填充TableView

解决Xcode中用Firebase子节点标题填充TableView的问题

Hey there! I see exactly what you're trying to do—you want to pull the Title1, Title2, Title3 keys from your Firebase database to populate your TableView, instead of the inner info fields. Let's get this sorted out step by step.

问题分析

Your current code is nesting an observeSingleEvent inside a .childAdded listener, which is overcomplicating things. The titles you need are actually the keys of the child nodes under your main folder (UserSaves/{uCode}). You don't need to dig into the inner info fields just to get these titles.

修正后的实现代码

Here's a cleaner approach that directly fetches the child node keys and populates your TableView:

// 1. 引用到你的主文件夹节点
let ref = Database.database().reference()
let mainFolderRef = ref.child("UserSaves").child(uCode)

// 2. 监听主文件夹的.value事件,一次性获取所有子节点
mainFolderRef.observe(.value, with: { snapshot in
    // 先清空旧数据,避免重复加载
    self.datas.removeAll()
    
    // 遍历所有子节点,每个child的key就是你要的Title
    for childSnapshot in snapshot.children {
        guard let child = childSnapshot as? DataSnapshot else { continue }
        let title = child.key // 这里就是Title1、Title2、Title3
        self.datas.insert(Ligne(titre: title), at: 0)
    }
    
    // 刷新TableView展示新数据
    self.tableView.reloadData()
})

// 可选:如果需要实时监听新增标题,用.childAdded事件
// mainFolderRef.observe(.childAdded, with: { snapshot in
//     let title = snapshot.key
//     self.datas.insert(Ligne(titre: title), at: 0)
//     self.tableView.reloadData()
// })

关键说明

  • snapshot.key:这就是你要的核心!主文件夹下的每个子节点(Title1、Title2等)的标识就是它的key,通过child.key就能直接拿到这个标题字符串。
  • .value vs .childAdded:如果只需要一次性加载所有标题,用.value;如果希望Firebase新增标题时TableView自动更新,就用.childAdded。
  • 内存管理:记得在视图控制器销毁时移除监听,避免内存泄漏。可以在viewWillDisappear或deinit中添加:
    mainFolderRef.removeAllObservers()
    

额外提示

如果之后需要获取某个标题下的info内容(比如用户点击TableView单元格时),可以用拿到的标题key直接定位到子节点:

let selectedTitle = datas[indexPath.row].titre
mainFolderRef.child(selectedTitle).observeSingleEvent(of: .value) { snapshot in
    let infoDict = snapshot.value as? [String: Any]
    let info1 = infoDict?["info1"] as? String ?? ""
    // 这里处理info数据
}

内容的提问来源于stack exchange,提问作者flyer74

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:58:13