2016-01-06 2 views
0

Когда я пытаюсь выполнить следующий код, функция self.returnImage(displayedPicture!, currentIteration: i, completion: self.printValue) должна иметь currentIteration из i, которая должна быть равна 0, однако при запуске кода она не равна i ,Ошибка индекса массива вне диапазона

for (var i = 0; i < self.numberOfImages; i++) { 
        let displayedPicture = object["productImage\(i)"] as? PFFile 
        self.returnImage(displayedPicture!, currentIteration: i, completion: self.printValue) 
        var oldI = -1 
        print(object.objectId) 
        print("oldI \(oldI)") 
        print("i = \(i)") 
        print("Getting objects") 
        // self.productImages.append((object["productImage\(i)"] as? PFFile)!) 
        print("oldI = i") 
        oldI++ 
       } 

Это то, что консоль печатает

  1. Успех
  2. На businessDetailsVC
  3. Количество изображений 2
  4. Количество объектов Необязательные (1)
  5. Необязательные ("H1b7iUj4PS ")
  6. старыйI -1
  7. = 0
  8. Получение объектов
  9. ОЛДИ = I
  10. Необязательные ("H1b7iUj4PS")
  11. ОЛДИ -1
  12. I = 1
  13. Получение объектов
  14. ОЛДИ =
  15. я
  16. currentIteration = 1
  17. Количество изображений = 2
  18. ImageViewArray Count = 1
  19. неисправимая ошибка: Индекс массива вне диапазона (lldb)

Это returnImage функция. Как будто функция опоздана, потому что она извлекает данные из бэкэнда Parse, это заметно, потому что вызываются prints до того, как функция вызывается, даже если она противоположна в коде.

func printValue(result: Bool) { 
    print("result = \(result)") 
} 

func returnImage(pictureFile: PFFile, let currentIteration: Int, completion: (result: Bool) -> Void) { 
    pictureFile.getDataInBackgroundWithBlock({ (imageData, error) -> Void in 
     if error != nil { 
      print(error) 
      completion(result: false) 
     } else { 
      if let data = imageData { 
       print("currentIteration = \(currentIteration)") 
       //var circleArray = Array<UIImageView>() 
       //var y : CGFloat = 0.0 
       //var i = 0 
       self.imageViewArray.append(UIImageView(frame:CGRectMake(self.screenWidth/2 - 120, self.screenHeight/2 - CGFloat(self.numberOfImages + 80), 120, 120))) 
       print("Number Of Images Count = \(self.numberOfImages)") 
       print("ImageViewArray Count = \(self.imageViewArray.count)") 

       self.imageView = self.imageViewArray[currentIteration] // This is the line where the Array index out of range occurs 

       self.imageView.image = UIImage(data: data)! 
       self.imageView.tag = currentIteration 
       self.view.addSubview(self.imageView) 

       //self.imageView[i].frame = CGRectMake(self.screenWidth/2 - 120, self.screenHeight/2 - CGFloat(self.numberOfImages + 10), 60, 60) 
       //self.imageView[i].image = UIImage(data: data)! 
       self.imageView.contentMode = UIViewContentMode.ScaleAspectFill 
       self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2 
       self.imageView.clipsToBounds = true 

      } 
     } 

     completion(result: true) 
    }) 
} 

Это полный код. Индекс массива из ошибок диапазона происходит на линии с self.imageView = self.imageViewArray[currentIteration]

import UIKit 
import Parse 

class BusinessDetailsVC: UIViewController, UIScrollViewDelegate { 

var businessTitle: String = "" 

let scrollView: UIScrollView = UIScrollView() 

let screenHeight = UIScreen.mainScreen().bounds.size.height 
let screenWidth = UIScreen.mainScreen().bounds.size.width 

var numberOfImages: Int = 0 

var nameOfImage: [String] = [String]() 

var productImages: [PFFile] = [PFFile]() 

var downloadedImage: UIImage = UIImage() 

var imageViewArray = Array<UIImageView>() 
var imageView: UIImageView = UIImageView() 

//var displayedPicture: [PFObject] = [PFObject]() 
//var imageView = UIImageView() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    print("On businessDetailsVC") 

    let query = PFQuery(className: "C_h0usYnpEqL") 

    print("Number of images \(numberOfImages)") 
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in 

     if error != nil { 
      print(error) 
     } else if objects! == objects! { 
      print("Number of objects \(objects?.count)") 
      for object in objects! { 
       for (var i = 0; i < self.numberOfImages; i++) { 
        let displayedPicture = object["productImage\(i)"] as? PFFile 
        self.returnImage(displayedPicture!, currentIteration: i, completion: self.printValue) 
        var oldI = -1 
        print(object.objectId) 
        print("oldI \(oldI)") 
        print("i = \(i)") 
        print("Getting objects") 
        // self.productImages.append((object["productImage\(i)"] as? PFFile)!) 
        print("oldI = i") 
        oldI++ 
       } 
      } 
     } 
    } 


} 

func printValue(result: Bool) { 
    print("result = \(result)") 
} 

func returnImage(pictureFile: PFFile, let currentIteration: Int, completion: (result: Bool) -> Void) { 
    pictureFile.getDataInBackgroundWithBlock({ (imageData, error) -> Void in 
     if error != nil { 
      print(error) 
      completion(result: false) 
     } else { 
      if let data = imageData { 
       print("currentIteration = \(currentIteration)") 
       //var circleArray = Array<UIImageView>() 
       //var y : CGFloat = 0.0 
       //var i = 0 
       self.imageViewArray.append(UIImageView(frame:CGRectMake(self.screenWidth/2 - 120, self.screenHeight/2 - CGFloat(self.numberOfImages + 80), 120, 120))) 
       print("Number Of Images Count = \(self.numberOfImages)") 
       print("ImageViewArray Count = \(self.imageViewArray.count)") 

       self.imageView = self.imageViewArray[currentIteration] // This is the line where the Array index out of range occurs 

       self.imageView.image = UIImage(data: data)! 
       self.imageView.tag = currentIteration 
       self.view.addSubview(self.imageView) 

       //self.imageView[i].frame = CGRectMake(self.screenWidth/2 - 120, self.screenHeight/2 - CGFloat(self.numberOfImages + 10), 60, 60) 
       //self.imageView[i].image = UIImage(data: data)! 
       self.imageView.contentMode = UIViewContentMode.ScaleAspectFill 
       self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2 
       self.imageView.clipsToBounds = true 

      } 
     } 

     completion(result: true) 
    }) 
} 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

Это бэкенд, где хранится объект, с двумя файлами изображений для его извлечения This is the backend where the object is stored, with two image files being retrieved

ответ

0

В соответствии с текущей логикой, попытайтесь добавьте ImageView с кодом ниже,

self.imageViewArray.append(UIImageView(frame:CGRectZero)) 

Потому что, если возникла ошибка, у вас будет меньше изображений в массиве для следующей итерации. , например. Если в итерации 3 возникла ошибка, то для следующей итерации 4 вы получите только 3 изображения, если итерация 4 будет успешной.

+0

, который только изменил положение UIImageView, он не изменил, имел ли массив индекс вне диапазона или нет – questionaire