数组索引超出范围。迅速。表视图

时间:2016-02-02 19:24:44

标签: arrays swift image tableview

我遇到致命错误:数组索引超出范围。当tempProductPictureArray [count]为nil时,错误来自let profilePicture = tempProductPictureArray[count]。我想知道我在imageArray上设置了什么错误吗?

var imageArray = [[PFFile]]()
........
.......
.......
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell:MarketTableViewCell = tableView.dequeueReusableCellWithIdentifier("MarketCell") as! MarketTableViewCell
    let tempProductPictureArray = imageArray[indexPath.row]
    // tempProductPictureArray.count is something like [nil / PFFile(image), nil / PFFile(image) .....]
    if tempProductPictureArray.count != 0 {
        var hasImage = false
        var count = 0
        while hasImage == false {
            let profilePicture = tempProductPictureArray[count]
            if profilePicture != nil {
                profilePicture!.getDataInBackgroundWithBlock { data, error in
                    if error != nil {
                        self.appDelegate.displayMyAlertMessage((error?.localizedDescription)!, userVI: self)
                    } else {
                        cell.productImage.image = UIImage(data: data!)
                    }
                }
                hasImage = true
            } else if count == tempProductPictureArray.count {
                cell.productImage.image = UIImage(named: "Profile Picture")
            } else {
                count += 1
            }
        }
    } else {
        cell.productImage.image = UIImage(named: "Profile Picture")
    }

数据源

func refreshResults(){
    ...
    ...
    ...
sameObjectInQuery.findObjectsInBackgroundWithBlock{ (sameObjects: [PFObject]?, error: NSError?) -> Void in
    for var i = 0; i <= tempUniqueTitle.count - 1; i++ {
        tempProductImage = [PFFile]()
        for sameobject in sameObjects! {
             if sameobject.objectForKey("detailsImage") != nil {
                 tempProductImage.append(sameobject.objectForKey("detailsImage") as? PFFile)
             } else {
                 tempProductImage.append(nil)
             }
        imageArray.append(tempProductImage)
}
....

1 个答案:

答案 0 :(得分:1)

跟踪代码,假设tempProductPictureArray包含一个项目。 tempProductPictureArray.count将为1,该项目位于偏移0.大概是,它是一个可选的,你想跳过它。

由于count不等于tempProductPictureArray.count,因此您需要添加一个来计数并尝试从该位置的数组中获取某些内容(偏移量1)。但是,我们已经说过数组中唯一的元素是偏移0,所以......崩溃。

您需要确保count始终小于tempProductPictureArray.count

相关问题