如何获得Realm数据库上的名称列表并显示在我的刺激器上?

问题描述 投票:0回答:2

这里我有一个领域数据库,其中包含一些数据,我想将其显示在我的Stimulator上,但结果却显示了其他内容。我的代码有什么问题?

这是我的领域数据库的数据,我也标记了要显示的数据。

enter image description here

显示类似这样的刺激物。

enter image description here

这是我的ViewController.swift代码。

import UIKit
import RealmSwift

class ViewController: UIViewController,UITableViewDataSource  { //UITableViewDataSource

    @IBOutlet weak var mytableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let realm = try! Realm()
         let theItem = realm.objects(Item.self).filter("itemid >= 1")
         return theItem.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let realm = try! Realm()
        let theItem = realm.objects(Item.self).filter("itemid >= 1")
        print(theItem)

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
        //I suspect the problem is at here...
        cell?.textLabel?.text = "\(theItem)"
        return cell!

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

}

class Category: Object {
    @objc dynamic var name: String?
    @objc dynamic var caid: Int = 0
}

class Item: Object {
    @objc dynamic var name: String?
    @objc dynamic var itemid: Int = 0
    @objc dynamic var cateid: Int = 0
}
ios swift database realm
2个回答
1
投票

您的问题是您需要从Item对象获取字符串。尝试类似

"\(theItem.name)"


-1
投票
var items: [Item] = [] {
        didSet {
            DispatchQueue.main.async {
                // Reloads the tableview when even any change occurs to items array.
                tableview.reloadData()
            }
        }
    }

在Viewdidload呼叫getItems()

func getItems() {
let realm = try! Realm()
    self.items = realm.objects(Item.self).filter("itemid >= 1")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
    cell?.textLabel?.text = items[indexPath.row].name
    return cell!

}
© www.soinside.com 2019 - 2024. All rights reserved.