Swift:UICollectionView& UIImage致命错误:数组索引超出范围

时间:2015-07-19 16:33:17

标签: swift parse-platform uiimage

嗨,我是swift的新手,需要一些帮助,谢谢。该程序工作一次,试图再次运行然后崩溃。我调试时,这些项目在数组中,但是当我尝试显示图像时,我得到了致命的错误。

    // Get Brands
    func getBrand () {

        // Create PFQuery
        var query:PFQuery = PFQuery(className: "BrandInfo")

        // Call findobjects
        query.findObjectsInBackgroundWithBlock {
            (objects:[AnyObject]?, error: NSError?) -> Void in

            // refresh array
            self.brands = [String]()
            self.pics = [UIImage]()

            // loop through array
            for brandObject in objects! {

            // get PFObjects
            let brandName:String? = (brandObject as! PFObject)["Name"] as? String

                if brandName != nil {
                    self.brands.append(brandName!)

                }

            let brandPicture = brandObject["Image"] as! PFFile
                brandPicture.getDataInBackgroundWithBlock({ (imageData:NSData?, error:NSError?) -> Void in

                    if(error == nil){

                    let brandImage = UIImage(data: imageData!)
                        self.pics.append(brandImage)

                        println(self.pics.count)
                    }
                })

    }
        // Refresh CollectionView
        self.collectionView.reloadData()

}

}

// Setting up collection view
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.brands.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell:collectionViewCell = self.collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! collectionViewCell

    // Get elements
    let picToDisplay:UIImage? = pics[indexPath.row]  // this is the error line
    let dataToDisplay:String = brands[indexPath.row]

    let imageView:UIImageView? = cell.viewWithTag(2) as? UIImageView


    // Set labels
    cell.brandImage.image = picToDisplay
    cell.brandLabel.text = dataToDisplay


    return cell

}

///////////////////////////////

struct brandCollection {

    var brandText:[String] = [String]()
    var brandImage:[UIImage?] = [UIImage]()

}

1 个答案:

答案 0 :(得分:0)

您有brands.count项,并且需要brand.count张图片。但是您使用的是另一个数组pics,如果它的元素少于brands,则会失败。看看你的代码,有几种可能性可能发生。

这是糟糕的设计。您应该有一个数据数组,它封装了您需要的所有信息。每个图像都应连接到其对象(品牌),而不是保存在其他阵列中。