2017-02-01 31 views
0

我成功地從Realm數據庫下載和打印數據。這裏是我的日誌:來自Realm數據庫的tableview中的項目列表

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"))) 

現在我必須在實際列表上分配這些值,我得到一個乾淨的工作表tableview。如何正確地做到這一點?我使用.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 
    } 

} 
+0

你鏈接了tableView代表嗎? results.count肯定是> 0,並且'cellForRowAt'曾經被調用過? – Russell

+0

是的,它們是鏈接的。調試完畢後 - > po results.count - 它給我0..cellForRow甚至沒有被調用。 – Vuko

+0

如果result.count == 0,'cellForRowAt'永遠不會被調用 - 意味着問題不是tableView,而是數據檢索。 – Russell

回答

0

我覺得你從響應中獲取數據後缺少'self.tableView.reloadData()'。考慮將獲取的數據分配給結果變量。

+0

這不是不幸的。你提取的數據是什麼意思,你能舉個例子嗎? – Vuko

+0

將「結果」更改爲變量,並在調用「self.tableView」後將此行更改爲'_ = self.realm.objects(ItemRealm.self)'改爲'self.results = self.realm.objects(ItemRealm.self)' .reloadData()」 –

相關問題