为什么我的对象被添加了 6 次?

问题描述

我正在尝试使用 segue 和一个按钮将我的对象从 hockeyDetailVC 转移到 FavouritesVC,从一个 tableView 转移到另一个 tableView。

override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    if segue.identifier == "r" {
    let destinationController = segue.destination as! FavouritesVC
    destinationController.currentFav = item!
}
}

但问题是它转移了我的对象 6 次,我不确定它为什么这样做,它应该只转移一次。

override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
favArr.append(currentFav!)
print("this is how many players there are: \(favArr.count)") //At the end of execution gives me 6 players.
return favArr.count
}



var item: CurrentPlayers?          //This is what I want to transfer in my hockeyDetailVC

var currentFav: CurrentPlayers?    //This is the variable I set my transfer in FavouritesVC

class CurrentPlayers {
var photoUrl: String
var position: String
var team: String
var yahooName: String
var birthCity: String
var birthState: String
var status: String
var catches: String
var shoots: String
var jerseyNumber: Int
var largePhoto: String

init(photoUrl: String,position: String,team: String,yahooName: String,birthCity: String,status: String,catches: String,shoots: String,birthState: String,jerseyNumber: Int,largePhoto: String) {
    
    self.yahooName = yahooName
    self.photoUrl = photoUrl
    self.position = position
    self.team = team
    self.birthCity = birthCity
    self.status = status
    self.catches = catches
    self.shoots = shoots
    self.birthState = birthState
    self.jerseyNumber = jerseyNumber
    self.largePhoto = largePhoto

}
}

解决方法

numberOfRowsInSection 必须返回给定部分中的项目数,没有别的。

删除

favArr.append(currentFav!)

从方法中放入viewDidLoad