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

Swift中如何创建数据模型并在UITableView中加载?

用数据模型重构UITableView数据加载代码

1. 创建单条记录的数据模型

先定义一个结构体来封装单条锻炼历史的所有属性,替代原来分散的多个数组:

import Foundation

// 单条锻炼历史记录模型
struct ExerciseHistory: Codable {
    let dayNumber: String
    let date: String
    let time: String
    let completedExerciseNames: [String]
}

2. 替换多数组为模型数组

删除原来的getCompletedExerciseNamesArray、getCompletedDayArray等数组,改用一个存储模型实例的数组:

let filemanager = FileManager.default
var folderNameArray = [String]()
// 用这个数组替代所有分散的数组
var exerciseHistoryRecords: [ExerciseHistory] = []

3. 重构数据加载方法

修改getAllSavedDictionary方法,将字典数据解析为模型实例并添加到数组中,同时优化可选值处理和性能:

func getAllSavedDictionary() {
    // 先清空旧数据
    exerciseHistoryRecords.removeAll()
    
    guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first else {
        return
    }
    
    for folderName in folderNameArray {
        let fileURL = URL(fileURLWithPath: documentPath).appendingPathComponent(folderName)
        guard let dictionary = NSMutableDictionary(contentsOf: fileURL) else {
            continue
        }
        
        // 安全解析所有数组,确保长度一致避免数据不匹配
        guard let dayNumbers = dictionary.value(forKey: "DayNumber") as? [String],
              let dates = dictionary.value(forKey: "DayDate") as? [String],
              let times = dictionary.value(forKey: "DayTime") as? [String],
              let exerciseNamesList = dictionary.value(forKey: "completedExerciseNames") as? [[String]],
              dayNumbers.count == dates.count, dates.count == times.count, times.count == exerciseNamesList.count else {
            continue
        }
        
        // 遍历数组生成模型实例
        for index in 0..<dayNumbers.count {
            let record = ExerciseHistory(
                dayNumber: dayNumbers[index],
                date: dates[index],
                time: times[index],
                completedExerciseNames: exerciseNamesList[index]
            )
            exerciseHistoryRecords.append(record)
        }
    }
    
    // 所有数据加载完成后统一刷新表格
    historyTableview.reloadData()
}

4. 配置UITableView数据源

修改表格的数据源方法,直接用模型数组配置单元格:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return exerciseHistoryRecords.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 替换为你的单元格标识符
    let cell = tableView.dequeueReusableCell(withIdentifier: "HistoryCell", for: indexPath)
    
    let record = exerciseHistoryRecords[indexPath.row]
    // 根据你的单元格布局配置内容
    cell.textLabel?.text = "Day \(record.dayNumber) | \(record.date)"
    cell.detailTextLabel?.text = "时间:\(record.time)\n完成练习:\(record.completedExerciseNames.joined(separator: "、"))"
    
    return cell
}

关键优化说明

  • 用Swift原生URL替代NSURL、NSMutableString,更符合现代Swift写法
  • 移除强制解包(!),用guard let安全处理可选值,避免崩溃
  • 将表格刷新放在循环结束后,减少不必要的UI刷新,提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:47:49