【发布时间】:2016-02-29 21:33:37
【问题描述】:
我正在尝试从解析中查询图像,当我打开我的应用程序时一切正常,但如果我尝试刷新,我会得到如下所示的崩溃...
不太清楚是什么原因造成的...解释一下我是如何设置的:
我有一个带有 1 个单元格的 tableView,在那个单元格中有三个 imageView 连接到一个集合 Outlet。然后我从解析中获取我的图像并将它们放在我的 imageViews 中,然后在 numberOfRowsInSection 中我将它除以 3,这样它就不会重复图像 3 次......!
下面是我的代码:
var countries = [PFObject]()
override func viewDidLoad() {
super.viewDidLoad()
loadPosts()
// Do any additional setup after loading the view.
}
func loadPosts() {
PFUser.query()
// Build a parse query object
let query = PFQuery(className:"Post")
query.whereKey("user", equalTo: PFUser.currentUser()!)
query.orderByDescending("createdAt")
// Fetch data from the parse platform
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
// The find succeeded now rocess the found objects into the countries array
if error == nil {
self.countries.removeAll(keepCapacity: true)
if let objects = objects {
self.countries = Array(objects.generate())
}
// reload our data into the collection view
self.tableView.reloadData()
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return countries.count / 3
}
var counter = 0
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell2") as! bdbTableViewCell
for imageView in cell.threeImages {
let placeHolder = UIImage(named: "camera")
imageView.image = placeHolder
let finalImage = countries[counter++]["imageFile"]
finalImage!.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
imageView.image = UIImage(data:imageData)
}
}
}}
return cell
}
【问题讨论】:
-
您还应该学习如何调试。您的代码第一次工作主要是因为运气,但如果您刷新,或者当您滚动并且单元格离开屏幕并重新打开时,它真的不会工作。您为 counter 使用一个类变量,每次显示或重新显示单元格时,它都会简单地增加 3。这将导致它大于图像数组。您为单元格加载的图像应该基于传递给方法的 indexPath,而不是永远不会重置的计数器。有关详细信息,请参阅下面的答案。
标签: ios swift parse-platform tableview