我正在尝试从Parse获取数据并填充表视图控制器。我在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("")*/
}
}
在viewWillAppear中的我试图从Parse后端获取数据并用它填充表。当我运行该程序时,我收到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
错误是由numberOfRowsInSection中的objectsArray.count行引起的。足够公平......它试图获得计数,但显然数组是空的,因为获取数据的工作是在后台运行而尚未完成。这是我需要帮助的。我是否将获取代码放在正确的位置(即viewWillAppear)?如果没有,我应该把它放在哪里,以确保它在表实际尝试加载之前执行。
谢谢,
答案 0 :(得分:1)
您必须像其他人一样初始化PFObject
数组。
var objectsArray = [PFObject]()
并且您必须在填充reloadData()
之后立即在主线程上的表视图实例上调用objectsArray
。
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()
}