简体   繁体   English

Swift-用数据填充表视图

[英]Swift - Populating Table View with Data

I am trying to fetch data from Parse and populate a table view controller. 我试图从解析中获取数据并填充表视图控制器。 I have the following defined in the VC: 我在VC中定义了以下内容:

class OrdersViewController: UITableViewController{


    /*************************Global Objects************************/
    var userObject = UserClass()
    var utilities = Utilities()
    var orderObject = OrderClass()
    var objectsArray:[PFObject]!
    /*************************UI Components************************/

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        SwiftSpinner.show("Please Wait...Populating Table")

        let query = PFQuery(className:"Orders")
        query.whereKey("appUsername", equalTo:PFUser.currentUser()!["appUsername"])
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in

            if error == nil {
                SwiftSpinner.hide()
                self.objectsArray = objects
            } else {
                SwiftSpinner.hide()

                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }

        SwiftSpinner.hide()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "cell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! OrderCell

        let row = indexPath.row
        cell.orderRetailerName.text = objectsArray[row]["nameRetailer"] as? String
        cell.status.text = objectsArray[row]["status"] as? String
        cell.dueDate.text = objectsArray[row]["dueDate"] as? String

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        /*tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        print("")*/
    }

}

in the viewWillAppear I am trying to fetch the data from the Parse backend and populate the table with it. 在viewWillAppear中,我试图从Parse后端获取数据并用它填充表。 When I run the program, I am getting the following error: 运行该程序时,出现以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

the error is caused by objectsArray.count line in numberOfRowsInSection. 该错误是由numberOfRowsInSection中的objectsArray.count行引起的。 Fair enough...It is trying to get the count but clearly the array is empty because the job of fetching data is running in background and isn't completed yet. 足够公平……它试图获取计数,但显然数组为空,因为获取数据的工作在后台运行,并且尚未完成。 This is what I need help with. 这是我需要帮助的。 Am I placing the fetching code in the right location (ie viewWillAppear)? 我是否将获取代码放置在正确的位置(即viewWillAppear)? If not, where should I put it instead to ensure it executes before the table actually attempts loading. 如果没有,我应该放在哪里,以确保它在表实际尝试加载之前执行。

Thanks, 谢谢,

You have to initialize the PFObject array like the others. 您必须像其他PFObject一样初始化PFObject数组。

var objectsArray = [PFObject]()

and you have to call reloadData() on the table view instance on the main thread right after populating objectsArray . 并且您必须在填充objectsArray之后立即在主线程上的表视图实例上调用reloadData()

query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in
     if error == nil {
        self.objectsArray = objects!
        dispatch_async(dispatch_get_main_queue()) {
          self.tableView.reloadData()
        }
     } else {
        // Log details of the failure
        print("Error: \(error!) \(error!.userInfo)")
     }
     SwiftSpinner.hide()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM