我正在尝试从 parse.com 获取一些字符串和一张照片作为表格 View 。我有一个此类的 NSObject 以及一个用于存储它们的对象数组。当尝试获取 newsPhoto 时,我可以按正确的顺序获取 newsTitle 和 newsDetail,但失败了。我想当尝试获取 block 中的图像时它丢失了顺序。有谁知道我应该对下面的代码进行哪些更改来修复它?
func getNews(){
let query = PFQuery(className: "bulletinOnParse")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(allNews: [PFObject]?, error: NSError?) -> Void in
if error == nil {
var duyuru:News
for news in allNews! {
duyuru = News()
let nTitle = news.objectForKey("title") as! String
duyuru.newsTitle = nTitle
let nDetail = news.objectForKey("comment") as! String
duyuru.newsDetail = nDetail
let imageFile = news["newsphoto"] as! PFFile
imageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
duyuru.newsPhoto = image!
}
}
}
self.bulletin += [duyuru]
}
} else {
// Log details of the failure
print("\(error!.userInfo)")
}
self.tableView.reloadData()
}
}
以及下面的 cellForRowAtIndexPath 方法
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DuyuruTableViewCell
self.tableView.rowHeight = 100
let cellInfo = bulletin[indexPath.row]
cell.newsTitle.text = cellInfo.newsTitle
cell.news.text = cellInfo.newsDetail
dispatch_async(dispatch_get_main_queue(), {
cell.newsPhoto.image = cellInfo.newsPhoto
})
return cell
}
最佳答案
这是我如何解决问题的答案;
首先,我从 PFFile 对象创建了一个图像数组
var resultUserImageFiles = [PFFile]()
然后我获取名称并在 getNews() 方法上添加数组
self.resultUserImageFiles.append(news.objectForKey("newsphoto") as! PFFile)
我在 cellForRowAtIndexPath 方法中通过以下方法获取单元格的每张照片。
self.resultUserImageFiles[indexPath.row].getDataInBackgroundWithBlock { (imageData: NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.newsPhoto.image = image
}
}
关于swift - 按正确的顺序从解析中获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710029/