我正在从Parse中检索一组图像,使用以下代码使用Swift。
var imageResources : Array<UIImage> = []
override func viewDidLoad(){
super.viewDidLoad()
self.loadImages()
}
func loadImages(){
var query = PFQuery(className: "Images")
query.orderByDescending("objectId")
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
for object : PFObject! in objects as [PFObject] {
var thumbNail = PFFile()
thumbNail = object["image"] as PFFile
println("thumNail \(thumbNail)")
thumbNail.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) in
if (error == nil) {
let image : UIImage = UIImage(data:imageData)
//image object implementation
self.imageResources.append(image)
}
})//getDataInBackgroundWithBlock - end
}//for - end
}
else{
println("Error in retrieving \(error)")
}
})//findObjectsInBackgroundWithblock - end
}
我的Parse Class详细信息
班级名称 - 图片
当我运行此功能时,它会在控制台中没有消息而崩溃。
注意:我能够在回调中获得PFFile对象的集合。
我已经换了 “thumbNail.getDataInBackgroundWithBlock({....”块与同步函数调用thumbNail.getData()之类似 “var imageData = thumbNail.getData() var image = UIImage(data:imageData)“
然后错误说
警告:正在主线程上执行长时间运行的操作。 打破warnBlockingOperationOnMainThread()进行调试。
所以,我恢复了thumbNail.getDataInBackGroundWithBloack({... 但是现在,控制台中没有错误显示,因为之前发生过。我的方法有什么问题请告诉我。 任何帮助将不胜感激......!
答案 0 :(得分:6)
我设法重新创建了错误,这似乎是PFObject上的某种内存泄漏/僵尸。我不确定为什么,但是以下面的方式重构你的代码摆脱了我的错误:
func loadImages() {
var query = PFQuery(className: "Images")
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) {
let image = UIImage(data:imageData)
//image object implementation
self.imageResources.append(image)
println(image)
}
})//getDataInBackgroundWithBlock - end
}//for - end
}
编辑:顺便提一下,这也有效:
func loadImages() {
var query = PFQuery(className: "Images")
query.orderByDescending("objectId")
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
let imageObjects = objects as [PFObject]
for object in objects {
let thumbNail = object["image"] as PFFile
thumbNail.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
let image = UIImage(data:imageData)
//image object implementation
self.imageResources.append(image)
println(image)
}
})//getDataInBackgroundWithBlock - end
}//for - end
}
else{
println("Error in retrieving \(error)")
}
})//findObjectsInBackgroundWithblock - end
}
这表示该错误是由以下行引起的:
for object : PFObject! in objects as [PFObject] {
重写该行,如下所示:
for object : PFObject in objects as [PFObject] {
同时删除错误。所以这个错误的原因似乎是你告诉程序解开一些不可选的东西。