您好我是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
}
希望你们能够理解这段代码。
答案 0 :(得分:1)
使用该调度块的正确方法如下:
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()
}