嗨,我是 swift 和 parse.com 的新手,我正在尝试用解析中已保存的图像填充我的数组,尝试使用dispatch_async,但不知道这是如何工作的,代码如下:
//imageArray declaration in table:
var imageArray: Array<UIImage> = []
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
var query = PFQuery(className: "ParseClass")
query.findObjectsInBackgroundWithBlock { ( objects: [AnyObject]?, error: NSError?) -> Void in
if(error == nil) {
let imageObjects = objects as! [PFObject]
for object in objects! {
let thumbNail = object["columnInParse"] as! PFFile
thumbNail.getDataInBackgroundWithBlock ({ (imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
if let image = UIImage(data:imageData!) {
//here where the error appears: Cannot invoke 'dispatch_async' with an argument list of type '(dispatch_queue_t!, () -> _)'
dispatch_async(dispatch_get_main_queue()) {
cell.image.image = self.imageArray.append( image )
}
}
}
})
}
}
else{
println("Error in retrieving \(error)")
}
}
return cell
}
希望大家理解该代码。
最佳答案
使用该调度 block 的正确方法如下:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//perform your work here
self.imageArray.append(image)
cell.image.image = imageArray[indexPath.row]
})
编译器发出此警告的另一个原因是您尝试将图像附加到数组并将其设置为单元格图像。上面显示了您应该做什么。
最后,我建议将您的查询从 cellForRowAtIndexPath:
移出并移至单独的方法中,因为这是糟糕的代码设计。
编辑:重写方法以提供良好代码设计的示例...
var imageArray = [UIImage]()
func performLookupQuery() {
var query = PFQuery(className: "ParseClass")
query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?)
if error == nil {
let imageObjects = objects as! [PFObject]
for object in imageObjects {
let thumbnail = object["columnInParse"] as! PFFile
thumbnail.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?)
if error == nil {
if let image = UIImage(data: imageData!) {
imageArray.append(image)
//now your imageArray has all the images in it that you're trying to display
//you may need to reload the TableView after this to get it to display the images
}
}
}
}
}
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.image.image = nil
cell.image.image = imageArray[indexPath.row]
return cell
}
我没有像您应该的那样在查询方法中添加所有错误检查,我只是编写它来展示您会做什么。现在您已经有了这个查询方法,您可以在 viewDidLoad
中调用它,然后当您尝试加载表格时,结果将可用。
override func viewDidLoad(animated: Bool) {
super.viewDidLoad(animated)
self.performLookupQuery()
}
关于xcode - 在 swift 中使用解析填充图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732822/