我想调用 TableViewData Sources 方法,以便在从 parse 中提取 Ui 后设置它。有了这个我就可以获取
func loadImages() {
var query = PFQuery(className: "TestClass")
query.orderByDescending("objectId")
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
self.getImageData(objects as [PFObject])
}
else{
println("Error in retrieving \(error)")
}
})//findObjectsInBackgroundWithblock - end
}
func getImageData(objects: [PFObject]) {
for object in objects {
let thumbNail = object["image"] as PFFile
println(thumbNail)
thumbNail.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
var imageDic = NSMutableArray()
self.image1 = UIImage(data:imageData)
//image object implementation
self.imageResources.append(self.image1!)
println(self.image1)
println(self.imageResources.count)
}
}, progressBlock: {(percentDone: CInt )-> Void in
})//getDataInBackgroundWithBlock - end
}//for - end
self.tableView.reloadData()
但是不能像这样将这些获取的数据填充到tableview
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("in table view")
println(self.imageResources.count)
return imageResources.count+1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
var (title, image) = items[indexPath.row]
cell.loadItem(title: title, image: image)
println("message : going upto this line")
println(self.imageResources.count)
var (image1) = imageResources[indexPath.row]
cell.loadItem1(image1: image1)
return cell
}
然后在 loaditem 上我试图显示图像并且我已经写了我自己的数组来填充到图像数组但是我在填充时得到一个零值所以无法设置它
非常感谢任何帮助!
最佳答案
您有几个问题,都与并发有关 - 您的负载是在后台并行发生的。
第一个问题是在加载过程中使用self.image1
作为临时变量——这个变量可能被多个线程并发访问。为此,您应该使用局部变量。
其次,您从多个线程追加到 self.imageResources
,但 Swift 数组不是线程安全的。
第三,在加载完所有数据后,您需要在 tableview 上调用 reload,现在不会发生这种情况,因为您在后台操作仍在进行时调用它。
最后,您的 getImageData
函数在后台队列上执行,您必须在主队列上执行 UI 操作(例如重新加载表格)。
最简单的选择是将获取缩略图加载更改为同步调用 - 这意味着您的缩略图将按顺序加载,并且可能比多个并行任务花费更长的时间,但更易于管理 -
func getImageData(objects: [PFObject]) {
for object in objects {
let thumbNail = object["image"] as PFFile
println(thumbNail)
let imageData? = thumbNail.getData
if (imageData != nil) {
let image1 = UIImage(data:imageData!)
//image object implementation
self.imageResources.append(image1!)
println(self.imageResources.count)
}
}//for - end
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
一种更复杂的方法是使用调度组并保持并行图像加载。为此,您需要保护对共享数组的访问
关于ios - 方法完成后加载 TableView 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27166165/