调用 TableViewCell 中的函数后变量变为 nil

Variable becomes nil after function in TableViewCell is called

我正在尝试将 URL 传递给 UITableViewCell class 中的多个函数。在@objc 函数(用于处理按钮触摸)中,字符串变量 (videoString) 工作得很好。常规函数在解包字符串时一直发现 nil。

我已经尝试调整可选的展开 (?/!)。无论我做什么,函数都找不到 nil。为了对此进行测试,我将 @objc 添加到有问题的函数中,当我单击连接按钮时它确实起作用了。

var videoString = String()

这个有效:

var parent:Home?
@objc func shareSheet() {
    let items = [URL(string: videoString)!]
    let ac = UIActivityViewController(activityItems: items, 
    applicationActivities: nil)
    parent?.present(ac, animated: true)
}

这也是:

@objc func setupPlayerView() {
    let videoURL = videoString
    if let url = URL(string: videoURL) {
        player = AVPlayer(url: url as URL)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = videoFrame.bounds
        videoFrame.layer.addSublayer(playerLayer)
        player?.play()
    } else {
        print("Invalid")
    }
}

这个没有...

func setupPlayerView() {
    let videoURL = videoString
    if let url = URL(string: videoURL) {
        player = AVPlayer(url: url as URL)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = videoFrame.bounds
        videoFrame.layer.addSublayer(playerLayer)
        player?.play()
    } else {
        print("Invalid")
    }
}

单元格样式:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    setupPlayerView()
    addSubview(videoFrame)
    addSubview(share)

    share.addTarget(self, action: #selector(shareSheet), for: .touchUpInside)

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

我希望 setupPlayerView() 接受 videoString,但它总是找到 nil 并打印 "Invalid"。我认为这与闭包有关,因为另一个函数正确地接受了它。

更新

我通过声明 URL 并将其传递给位于 cellForRowAt:

的 TableView 文件中的 AVPlayer 使其工作
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 
-> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! EpisodeCell
    let currentLastItem = episodes[indexPath.row]
    cell.episode = currentLastItem
    let videoURL = currentLastItem.videoString
    let postURL = URL(string: videoURL)
    cell.videoPlayerItem = AVPlayerItem.init(url: postURL!)
    return cell
}

然后到TableViewCell里面的函数:

    func setupPlayerView() {
        self.player = AVPlayer.init(playerItem: self.videoPlayerItem)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = videoFrame.bounds
        videoFrame.layer.addSublayer(playerLayer)
        player?.play()
    }