快速致命错误:指数超出范围

时间:2016-08-01 20:33:40

标签: ios arrays swift xcode

我提前道歉,我对斯威夫特很新。我正在尝试创建一个允许您从数组加载图像的应用程序,并且我不断获得fatal error: Index out of range。我实际上并不确定是什么导致它,因为当我在集合视图中按下图像将其发送到详细视图控制器时它会随机崩溃。这是我的数组的代码:

func loadArray(){

    imageArray = []

    let userImages = PFQuery(className: "Image")
    userImages.whereKey("user", equalTo: PFUser.currentUser()!)

    let query = PFQuery.orQueryWithSubqueries([userImages])

    query.includeKey("user")
    query.orderByDescending("createdAt")

    query.findObjectsInBackgroundWithBlock {(result: [PFObject]?, error: NSError?) -> Void in


        if let result = result {
            for object in result{

                let imageFromParse = object["imageFile"] as! PFFile
                imageFromParse.getDataInBackgroundWithBlock { (data: NSData?, error: NSError?) -> Void in
                    if let data = data {
                        let image = UIImage(data: data, scale: 0.05)!
                        print("image: \(image)")
                        self.imageArray.append(image)
                        print("doublecheck: " + String(self.imageArray))
                    }
                    if self.refreshControl.refreshing
                    {
                        self.refreshControl.endRefreshing()
                    }

                      self.cellView?.reloadData()
                    let targetIndexPath = NSIndexPath(forItem: self.imageArray.count-1, inSection: 0)
                    self.cellView?.reloadItemsAtIndexPaths([targetIndexPath])

                }
            }
        }

    }
    print("iamgeArray print \(self.imageArray)")
} 

这一行似乎有所突破:let passedImage = imageArray[realIndex.row] 当我将图像传递给详细视图时。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toDetailView" {
            let destController = segue.destinationViewController as! DetailViewController

            let selectedCellIndex = cellView.indexPathsForSelectedItems()
            let realIndex = selectedCellIndex![0]


            let passedImage = imageArray[realIndex.row]
            print(passedImage)
            print(selectedCellIndex)
            print(realIndex)
            destController.passedImageInDetailView = passedImage
        }
    }

如果您需要添加任何其他内容,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:0)

  1. 换行
let passedImage = imageArray[realIndex.row]

let passedImage = imageArray.dropFirst(realIndex.row).first
  1. 您的问题可能是func prepareForSegueloadArray()未完成时开始,因此调用imageArray = []
  2. 后会有一个空数组