[英]How to save a string array in realm (Swift)
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?谁能建议我如何将字符串数组(来自服务器)保存到 Realm 以在 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.如何转换数据变量,以便 Realm 可以使用它。 As far as I know, Realm does not work directly with String.
据我所知,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
}
}
Thank you very much in advance!非常感谢您!
Use List
for saving an array of strings in Realm.使用
List
将字符串数组保存在 Realm 中。 Check the following post for more information Realm with primitive types查看以下帖子以获取更多信息Realm 与原始类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.