iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
Mobile Development

我將成為Swift之強者系列 第 8

# Day 8 - 留言板實作:資料庫設計

  • 分享至 

  • xImage
  •  

Day 8 - 留言板資料庫設計

昨天我們完成了 Realm 的部署,今天要進一步思考 留言板需要哪些版面,並開始建立資料庫的資料結構。


留言板 MVC 架構

先來看看留言板的架構設計,整體會分為以下三個部分:

  • Model
    Data(資料庫)

  • View
    MainTableViewCell(自訂 Cell,顯示留言內容)

  • Controller
    MainViewController(留言板的主頁面控制器)

https://ithelp.ithome.com.tw/upload/images/20250922/20178625DDCs9s7ghI.png

建立資料庫 Model

Model 資料夾中新增一個 Swift 檔,命名為 Data.swift(不一定要跟我的一樣)
這個類別會負責定義每一筆留言的資料結構。

import Foundation
import RealmSwift

class MessageBoard: Object {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var name: String = ""        // 使用者名字
    @Persisted var content: String = ""     // 留言內容
    @Persisted var currentTime: String = "" // 留言時間

    // 初始化方法,方便建立新留言
    convenience init(name: String, content: String, currentTime: String) {
        self.init()
        self.name = name
        self.content = content
        self.currentTime = currentTime
    }
}

程式碼解析

  1. @Persisted(primaryKey: true) var _id: ObjectId
    自動生成的唯一 ID,確保每一筆留言不會重複。

  2. name
    存放留言者的名字。

  3. content
    存放留言的文字內容。

  4. currentTime
    存放留言時間,方便排序或顯示。

  5. convenience init(...)
    提供快速初始化方法,讓我們能夠輕鬆建立一筆新的留言資料。


小結

今天我們完成了 留言板的資料庫設計,並建立了 MessageBoard 模型。
它將會是整個留言板功能的核心,負責存放與管理所有留言資料。

明天我們會介紹 MainViewController 的 XIB 元件與程式碼


上一篇
Day 7 - 留言板實作前置動作:Realm 資料庫部署
系列文
我將成為Swift之強者8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言