【发布时间】:2017-02-01 21:26:06
【问题描述】:
我已成功从 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
}
}
【问题讨论】:
-
你链接了tableView代表吗? results.count 是否肯定 > 0,是否曾调用过
cellForRowAt? -
是的,它们是链接的。调试后 -> po results.count - 它给了我 0..cellForRow 甚至没有被调用。
-
如果 result.count == 0,
cellForRowAt将永远不会被调用 - 意味着问题不是 tableView,而是数据检索。 -
好吧。谢谢。有什么建议吗?
-
我还是不明白:你有 2 个数据库?
Server A = 192.168.1.101:8080和Server R = Realm然后您从服务器 A 请求项目并将项目移动到服务器 R 领域数据库?然后你再次从 Server R Realm 数据库中检索这些新项目?
标签: ios swift list uitableview realm