Когда я пытаюсь выполнить следующий код, функция 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++
}
Это то, что консоль печатает
- Успех
- На businessDetailsVC
- Количество изображений 2
- Количество объектов Необязательные (1)
- Необязательные ("H1b7iUj4PS ")
- старыйI -1
- = 0
- Получение объектов
- ОЛДИ = I
- Необязательные ("H1b7iUj4PS")
- ОЛДИ -1
- I = 1
- Получение объектов
- ОЛДИ = я
- currentIteration = 1
- Количество изображений = 2
- ImageViewArray Count = 1
- неисправимая ошибка: Индекс массива вне диапазона (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.
}
}
Это бэкенд, где хранится объект, с двумя файлами изображений для его извлечения
, который только изменил положение UIImageView, он не изменил, имел ли массив индекс вне диапазона или нет – questionaire