簡體   English   中英

如何在 realm (Swift) 中保存字符串數組

[英]How to save a string array in realm (Swift)

誰能建議我如何將字符串數組(來自服務器)保存到 Realm 以在 tableView 中顯示接收到的數據?

// Model
import UIKit
import RealmSwift

class MessageModel: Object, Decodable {
    @objc dynamic var result: [String]
}

如何轉換數據變量,以便 Realm 可以使用它。 據我所知,Realm 不能直接與字符串一起使用。

// ViewController
import UIKit
import RealmSwift

final class StartController: UIViewController {
 var data: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpView()
        setUpConstraints()
        configData()
    }

    private func configData() {
        service.addMessage(offset: offsetStart) { [weak self] result in
            switch result {
            case .success(let dataMessage):
                self?.data = dataMessage
                DispatchQueue.main.async {
                    self?.messageTable.reloadData()
                }
            case.failure(let error):
                print(error)
                DispatchQueue.main.async {
                    self?.showAlert(title: "Error", message: "Error connecting to the server")
                }
            }
        }
    }

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = messageTable.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
        cell.backgroundColor = UIColor(named: "backgroundColor")
        let messageList = data[indexPath.row]
        var content = cell.defaultContentConfiguration()
        content.text = messageList
        return cell
    }
}

非常感謝您!

使用List將字符串數組保存在 Realm 中。 查看以下帖子以獲取更多信息Realm 與原始類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM