在 Realm 数据库中的表视图中显示项目列表



我正在从 Realm 数据库下载和打印数据。这是我的日志:

Item(id: Optional(0), name: Optional("Item (0)"), descr: Optional("Description of item (0)"),
     icon: Optional("http://192.168.1.101:8080/api/items/0/icon.png"),
     url: Optional("http://192.168.1.101:8080/api/items/0")))

现在我必须在实际列表中分配这些值,并且我得到了一个干净的表视图。如何正确操作?我正在使用.xib作为tablewViewCell。我感谢任何提示。

class ItemRealm : Object {
    dynamic var id = 0
    dynamic var name = ""
    dynamic var desc = ""
    dynamic var icon = ""

    override class func primaryKey() -> String? {
        return "id"
    }
}

class ViewController: UIViewController, UITableViewDataSource,    UISearchBarDelegate {
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!

    let realm = try! Realm()
    let results = try! Realm().objects(ItemRealm.self).sorted(byKeyPath: "id")
    let SERVER_URL = "http://192.168.1.101:8080/api/items"
    override func viewDidLoad() {
        super.viewDidLoad()
        Alamofire.request(SERVER_URL).responseJSON { response in
            let items = [Item].from(jsonArray: response.result.value as! [Gloss.JSON])
            print(items?[0] as Any)
            try! self.realm.write {
                for item in items! {
                    let itemRealm = ItemRealm()
                    itemRealm.id = item.id!
                    itemRealm.name = item.name!
                    itemRealm.desc = item.descr!
                    itemRealm.icon = item.icon!
                    self.realm.add(itemRealm)
                }
            }
            _ = self.realm.objects(ItemRealm.self)
           // print(items?[0] as Any)
        }
        // Do any additional setup after loading the view.
        tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
    }
    // MARK: - UITableView data source
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return results.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        var object: ItemRealm
        object = self.results[indexPath.row] as ItemRealm
        cell.item = object
        return cell
    }
}

我认为您在从响应中获取数据后缺少self.tableView.reloadData()。还要考虑将提取的数据分配给结果变量。