2016-09-14 38 views
-2

我有一個朋友的數組,其相關信息的數組。我在表格視圖中渲染單元格,這很好。我可以導致應用程序崩潰,但如果我通過點擊屏幕上的大量點擊來向上/向下滾動...我無法理解爲什麼我的生活!Swift - 索引超出範圍的UITableVewController

這是錯誤:致命錯誤:超出範圍的索引

似乎有不被莫名其妙,爲什麼出現這種情況,這真的令人困惑。洞察力將不勝感激。

這是失敗等級:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PictureCell 
    let pos = self.positiveVoteArray.reduce(0,combine: {$0 + $1}) 
    let neg = self.negativeVoteArray.reduce(0,combine: {$0 + $1}) 
    let progress = (pos + neg)/pos 

//Fails below this line, first reference to indexPath.row // 
    cell.usernameBtn.setTitle(usernameArray[indexPath.row], forState: .Normal) 
    cell.uuidLbl.text = uuidArray[indexPath.row] 

    avaArray[indexPath.row].getDataInBackgroundWithBlock { (data:NSData?, error:NSError?) in 
     if error == nil { 
      cell.avaImg.image = UIImage(data: data!) 
     } 
    } 

    if votedFriendsArray.contains((PFUser.currentUser()?.username!)!) { 
     cell.scoreBar.hidden = false; 
     cell.dislikeBtn.hidden = true; 
     cell.likeBtn.hidden = true; 
     cell.scoreBar.setProgress(progress, animated: true) 

    } else { 
     cell.scoreBar.hidden = true; 
     cell.dislikeBtn.hidden = false; 
     cell.likeBtn.hidden = false; 
    } 

    picArray[indexPath.row].getDataInBackgroundWithBlock { (data:NSData?, error:NSError?) in 
     if error == nil { 
      cell.picImg.image = UIImage(data: data!) 
     } 
    } 

    // assign index 
    cell.usernameBtn.layer.setValue(indexPath, forKey: "index") 

    return cell 
} 
+2

你會在哪一行發生錯誤? –

+0

@SamM錯誤低於評論,第8行 – matt

回答

0

你最有可能設置在tableView(UITableView, numberOfRowsInSection: Int)錯誤的行數。它需要設置爲usernameArray.count,並且您需要確保它保持最新狀態(如果您要移除項目)。然後看下一行,uuidArray的計數必須與usernameArray相同。

+0

所以我使用usernameArray.count ..但也許我應該使用uuidArray.count。我正在做的是當我點擊一個單元格時,我導航到一個新的視圖,並推uuidArray [indexPath.row],當我回來時,我彈出。這通常很好,但如果我點擊/滾動一堆,我得到的錯誤.. 爲什麼這會**有時**導致錯誤? – matt

+0

檢查'uuidArray'的計數 - 它需要至少包含與'usernameArray'一樣多的項目。 – MirekE