我正在尝试遵循在线教程,将数据上传到iCloud并将数据从那里获取到我的tableView中。我已按照本教程进行操作,但是由于某些原因,我无法将数据加载到表视图中。我能够成功将数据上传到iCloud并进行查询,查询后我也可以将其打印出来。不知道我在做什么错。

我已经编写了一个查询数据库的函数,但是不确定为什么数据不会显示在tableView中。

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    let database = CKContainer.default().privateCloudDatabase

    var notes = [CKRecord]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")

        refreshControl.addTarget(self, action: #selector(queryDatabase), for: .valueChanged)

        self.tableView.refreshControl = refreshControl
        queryDatabase()
    }

    @objc func queryDatabase() {
        let query = CKQuery(recordType: "Note", predicate: NSPredicate(value: true))
        database.perform(query, inZoneWith: nil) { (records, _) in

            guard let records = records else { return }
            print(records)
            let sortedRecords = records.sorted(by: {$0.creationDate! > $1.creationDate!})

            self.notes = sortedRecords
            DispatchQueue.main.async {
               self.tableView.reloadData()
               self.tableView.refreshControl?.endRefreshing()
            }
        }
    }
}

extension ViewController: UITableViewDataSource {

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return notes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let note = notes[indexPath.row].value(forKey: "content") as! String
        cell.textLabel?.text = note
        return cell
    }
}


当我打印记录时,我得到类似


  [
  {
      creatorUserRecordID->
      lastModifiedUserRecordID->
      creationDate-> 2019-04-25 01:26:04 +0000
      修改日期-> 2019-04-25 01:26:04 +0000
      ModifyByDevice-> iPhone XR
      内容->“ HELLO”
  },
  {
      creatorUserRecordID->
      lastModifiedUserRecordID->
      creationDate-> 2019-04-25 02:42:03 +0000
      修改日期-> 2019-04-25 02:42:03 +0000
      ModifyByDevice-> iPhone XR
      内容->“嗨”
  }]


我想将所有记录加载到我的tableView中。

最佳答案

您的ViewController具有UITableViewDataSource协议的实现,但是tableView没有dataSource

tableView.reloadData()不执行任何操作,因为tableView不知道应该加载什么数据。

dataSource是The object that acts as the data source of the table view.
https://developer.apple.com/documentation/uikit/uitableview/1614955-datasource

在这个问题上,
tableView.dataSource = self中的viewDidLoad解决了该问题。

此代码告诉tableView从ViewController加载数据。

尽管行let cell = UITableViewCell()会产生另一个问题,但这是没有主题的。搜索如何重用UITableViewCell以提高tableView性能。

https://developer.apple.com/documentation/uikit/uitableview/1614878-dequeuereusablecell

10-07 19:49
查看更多