在Swift 3中将对象追加到数组

时间:2016-10-07 17:14:56

标签: swift

尝试将我从Parse查询的对象推送到可以在UITableView中使用的数组时遇到一些麻烦。

这是我的代码。

var locations = [AnyObject]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Query the Locations class.
    let query = PFQuery(className:"Location")

    query.findObjectsInBackground {
        (objects: [PFObject]?, error: Error?) -> Void in
        if error == nil {
            if let objects = objects {
                for object in objects {
                    self.locations.append(object)
                }
                self.venueTable.reloadData()
            }
        } else {
            // Log details of the failure
            print("Error: (error!) (error!.userInfo)")
        }
    }

}

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


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return locations.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let locationCell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)

    let location = locations[indexPath.row]

    locationCell.textLabel?.text = location

    return locationCell
}

在for循环之后,位置充满了解析数据,但在将其推送到locationCell

时无法确定如何访问它

1 个答案:

答案 0 :(得分:3)

您为位置设置的类型是[AnyObject],因此当您尝试设置标签文本属性时它将不起作用,因为它不是字符串。

而是将其设置为[PFObject],然后使用PFObject的函数objectForKey从检索到的对象中获取相关的字符串值。

例如

var locations = [PFObject]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Query the Locations class.
    let query = PFQuery(className:"Location")

    query.findObjectsInBackground {
    (objects: [PFObject]?, error: Error?) -> Void in
        if error == nil {
            if let objects = objects {

                self.locations = objects

                self.venueTable.reloadData()

            }

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

    }

}

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


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

     return locations.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let locationCell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)

    let location = locations[indexPath.row]

    locationCell.textLabel?.text = location.objectForKey("property name here") as? String

    return locationCell
}