Can anyone suggest how i can save a String array (which comes from the server) to Realm to display the received data in a tableView?
// Model
import UIKit
import RealmSwift
class MessageModel: Object, Decodable {
@objc dynamic var result: [String]
}
How to convert the data variable so that Realm can work with it. As far as I know, Realm does not work directly with String.
// 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
}
}
Thank you very much in advance!
Use List
for saving an array of strings in Realm. Check the following post for more information Realm with primitive types
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.