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

iOS开发中生命周期内数据不变的Model的最优创建方案是什么?

静态全生命周期不变Model的实现方案

没有绝对的“正确”写法,只看是否匹配你的业务需求,分两种场景给出对应方案:

场景1:数据仅在单一模块使用、量级极小、确认永久不会变更

直接在结构体/枚举中预置静态常量即可,足够简洁,不需要过度设计。你的现有写法只需要做2点优化即可符合不可变要求:

  1. 将Model的属性从var改为let,避免运行时意外修改
  2. 将预置数据声明为静态常量,全局唯一,不会重复初始化
    优化后代码示例:
// 基础数据模型,属性全为不可变
struct ExerciseCategoryModel {
    let title: String
    let image: UIImage?
}

// 统一管理分类列表的静态容器,用枚举避免被意外实例化
enum ExerciseCategoryStore {
    static let allCategories: [ExerciseCategoryModel] = [
        .init(title: "Chest", image: UIImage(named: "chest")),
        .init(title: "Back", image: UIImage(named: "back")),
        .init(title: "Shoulders", image: UIImage(named: "shoulders")),
        .init(title: "Quads", image: UIImage(named: "quads"))
    ]
}

ViewController中调用方式:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 省略cell复用逻辑
    let category = ExerciseCategoryStore.allCategories[indexPath.row]
    cell.label.text = category.title
    cell.rowImage.image = category.image
    return cell
}

场景2:数据多模块复用、后续可能支持动态配置(比如服务端下发、本地JSON配置)

建议抽离独立的静态资源Service层统一管理,好处是后续修改数据源不需要调整各业务调用方的代码,可维护性更高。
示例代码:

// 静态资源服务单例
class StaticResourceService {
    static let shared = StaticResourceService()
    private init() {}
    
    func getExerciseCategories() -> [ExerciseCategoryModel] {
        // 当前返回硬编码数据,后续可无缝切换为读本地JSON、接口缓存的静态配置等
        return [
            .init(title: "Chest", image: UIImage(named: "chest")),
            .init(title: "Back", image: UIImage(named: "back")),
            .init(title: "Shoulders", image: UIImage(named: "shoulders")),
            .init(title: "Quads", image: UIImage(named: "quads"))
        ]
    }
}

ViewController中调用方式:

class ExerciseViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    private var categories: [ExerciseCategoryModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        // 从服务层拉取数据
        categories = StaticResourceService.shared.getExerciseCategories()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 省略cell复用逻辑
        let category = categories[indexPath.row]
        cell.label.text = category.title
        cell.rowImage.image = category.image
        return cell
    }
}

最终建议

如果当前你的业务没有扩展需求,直接用第一种静态常量方案即可,是最简洁的实现;如果后续有扩展可能性,直接用Service层方案即可,避免后续重构成本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:06:01