这一挑战打击了我的信心,但有了韦恩的解决方案和一些耐心,我坚持了一整天,终于想出了一个似乎非常有效的解决方案。
代码:
func loadPhotoData() {
pageViews = []
pageImages = []
let query = PFQuery(className: "UserImages")
query.whereKey("user", equalTo: PFUser.currentUser())
query.addDescendingOrder("updatedPhotoAt")
query.findObjectsInBackgroundWithBlock { (objects: Array!, error: NSError!) -> Void in
if error != nil {
println("0 images found")
} else {
//index to assign to imgview tag to keep track of image in block
var idx = -1
var imageDictionary = Dictionary<Int, UIImage>()
for object in objects as Array {
idx++
var imageFile = object["image"] as PFFile
var imgView = PFImageView()
imgView.tag = idx
imgView.file = imageFile
imgView.loadInBackground({ (image: UIImage!, error: NSError!) -> Void in
if error != nil {
} else {
//store images in array for counting later
self.pageImages.append(image)
//store image index and image as dictionary value
imageDictionary[imgView.tag] = image
}
if objects.count == self.pageImages.count {
let sortedKeysAndValues = sorted(imageDictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues)
for (k,v) in Array(sortedKeysAndValues).sorted({$0.0 < $1.0}) {
println("\(k):\(v)")
self.pageImages[k] = v
}
打印日志:
[(0, <UIImage: 0x7fd5dac1df60>), (1, <UIImage: 0x7fd5d9455390>), (2, <UIImage: 0x7fd5da86a750>)]
0:<UIImage: 0x7fd5dac1df60>
1:<UIImage: 0x7fd5d9455390>
2:<UIImage: 0x7fd5da86a750>